-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcontract_verification.py
More file actions
169 lines (135 loc) · 5.11 KB
/
contract_verification.py
File metadata and controls
169 lines (135 loc) · 5.11 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
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
HTTP_REQUEST_TIMEOUT = 408
HTTP_SUCCESS = 200
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.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"
status_code, message, data = _do_post(url, request_dictionary)
if status_code == HTTP_REQUEST_TIMEOUT:
task_id = data.get("taskId", "")
if task_id:
query_status_with_task_id(verifier_url, task_id)
else:
dump_out_json(data)
elif status_code != HTTP_SUCCESS:
dump_out_json(data)
raise KnownError(f"Cannot verify contract: {message}")
else:
status = data.get("status", "")
if status:
logger.info(f"Task status: {status}")
dump_out_json(data)
else:
task_id = data.get("taskId", "")
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}")
status = response.get("status", "")
if status == "finished":
logger.info("Verification finished!")
dump_out_json(response)
break
elif status != old_status:
logger.info(f"Task status: {status}")
dump_out_json(response)
old_status = status
time.sleep(interval)
def _do_post(url: str, payload: Any) -> tuple[int, str, dict[str, Any]]:
logger.debug(f"_do_post() to {url}")
response = requests.post(url, json=payload)
try:
data = response.json()
message = data.get("message", "")
return response.status_code, message, data
except Exception as error:
logger.error(f"Erroneous response from {url}: {response.text}")
raise KnownError(f"Cannot parse response from {url}", error)
def _do_get(url: str) -> tuple[int, str, dict[str, Any]]:
logger.debug(f"_do_get() from {url}")
response = requests.get(url)
try:
data = response.json()
message = data.get("message", "")
return response.status_code, message, data
except Exception as error:
logger.error(f"Erroneous response from {url}: {response.text}")
raise KnownError(f"Cannot parse response from {url}", error)