-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcontract_verification.py
More file actions
175 lines (137 loc) · 5.34 KB
/
contract_verification.py
File metadata and controls
175 lines (137 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import hashlib
import json
import logging
import time
from pathlib import Path
from typing import Any, Optional, Protocol
import requests
from multiversx_sdk import Address, Message
from multiversx_sdk_cli.errors import KnownError
from multiversx_sdk_cli.utils import dump_out_json, read_json_file
logger = logging.getLogger("cli.contracts.verifier")
# fmt: off
class IAccount(Protocol):
def sign_message(self, message: Message) -> bytes:
...
# fmt: on
class ContractVerificationRequest:
def __init__(
self,
contract: Address,
source_code: dict[str, Any],
signature: bytes,
docker_image: str,
contract_variant: Optional[str],
) -> None:
self.contract = contract
self.source_code = source_code
self.signature = signature
self.docker_image = docker_image
self.contract_variant = contract_variant
def to_dictionary(self) -> dict[str, Any]:
return {
"signature": self.signature.hex(),
"payload": {
"contract": self.contract.to_bech32(),
"dockerImage": self.docker_image,
"sourceCode": self.source_code,
"contractVariant": self.contract_variant,
},
}
class ContractVerificationPayload:
def __init__(
self,
contract: Address,
source_code: dict[str, Any],
docker_image: str,
contract_variant: Optional[str],
) -> None:
self.contract = contract
self.source_code = source_code
self.docker_image = docker_image
self.contract_variant = contract_variant
def serialize(self) -> str:
payload = {
"contract": self.contract.to_bech32(),
"dockerImage": self.docker_image,
"sourceCode": self.source_code,
"contractVariant": self.contract_variant,
}
return json.dumps(payload, separators=(",", ":"))
def trigger_contract_verification(
packaged_source: Path,
owner: IAccount,
contract: Address,
verifier_url: str,
docker_image: str,
contract_variant: Optional[str],
):
source_code = read_json_file(packaged_source)
payload = ContractVerificationPayload(contract, source_code, docker_image, contract_variant).serialize()
signature = _create_request_signature(owner, contract, payload.encode())
contract_verification = ContractVerificationRequest(
contract, source_code, signature, docker_image, contract_variant
)
request_dictionary = contract_verification.to_dictionary()
url = f"{verifier_url}/verifier"
response = _do_post(url, request_dictionary)
task_id: str = response.get("taskId", "")
if not task_id:
raise KnownError("No task ID received from the verifier.")
logger.info(f"Contract verification triggered successfully. Task ID: {task_id}")
query_status_with_task_id(verifier_url, task_id)
def trigger_contract_verification_from_existing(contract: Address, verified_contract: Address, verifier_url: str):
payload = {
"contract": contract.to_bech32(),
"existingVerifiedContract": verified_contract.to_bech32(),
}
url = f"{verifier_url}/verifier/from-existing"
response = _do_post(url, payload)
task_id: str = response.get("taskId", "")
if not task_id:
raise KnownError("No task ID received from the verifier.")
logger.info(f"Contract verification triggered successfully. Task ID: {task_id}")
query_status_with_task_id(verifier_url, task_id)
def _create_request_signature(account: IAccount, contract_address: Address, request_payload: bytes) -> bytes:
hashed_payload: str = hashlib.sha256(request_payload).hexdigest()
raw_data_to_sign = f"{contract_address.to_bech32()}{hashed_payload}"
return account.sign_message(Message(raw_data_to_sign.encode()))
def query_status_with_task_id(url: str, task_id: str, interval: int = 10):
logger.info("Please wait while we verify your contract. This may take a while.")
old_status = ""
while True:
response = _do_get(f"{url}/tasks/{task_id}")
try:
response.raise_for_status()
except requests.HTTPError as error:
data = response.json()
message = data.get("message", str(error))
raise KnownError(f"Cannot verify contract: {message}", error)
response = response.json()
status = response.get("status", "")
if status == "error":
logger.error("Verification failed!")
dump_out_json(response)
break
elif status == "finished":
logger.info("Verification finished!")
dump_out_json(response)
break
elif status != old_status:
logger.info(f"Task status: {status}")
old_status = status
time.sleep(interval)
def _do_post(url: str, payload: Any) -> dict[str, str]:
logger.debug(f"_do_post() to {url}")
response = requests.post(url, json=payload)
try:
response.raise_for_status()
except requests.HTTPError as error:
data = response.json()
message = data.get("message", str(error))
raise KnownError(f"Cannot verify contract: {message}", error)
return response.json()
def _do_get(url: str) -> requests.Response:
logger.debug(f"_do_get() from {url}")
response = requests.get(url)
return response