@ethernity-cloud/sdk-js 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +185 -0
  3. package/build.js +22 -0
  4. package/init.js +301 -0
  5. package/nodenithy/build/las/Dockerfile +5 -0
  6. package/nodenithy/build/securelock/Dockerfile.tmpl +65 -0
  7. package/nodenithy/build/securelock/scripts/binary-fs-build.sh +28 -0
  8. package/nodenithy/build/securelock/src/.env +3 -0
  9. package/nodenithy/build/securelock/src/etny_crypto.js +201 -0
  10. package/nodenithy/build/securelock/src/etny_exec.js +65 -0
  11. package/nodenithy/build/securelock/src/image_registry_abi.js +808 -0
  12. package/nodenithy/build/securelock/src/models.js +261 -0
  13. package/nodenithy/build/securelock/src/package.json +40 -0
  14. package/nodenithy/build/securelock/src/pox_abi.js +1491 -0
  15. package/nodenithy/build/securelock/src/securelock.js.tmpl +421 -0
  16. package/nodenithy/build/securelock/src/swift_stream_service.js +147 -0
  17. package/nodenithy/build/securelock/src/task_status.js +15 -0
  18. package/nodenithy/build/securelock/src/wallet.js +29 -0
  19. package/nodenithy/build/squash/Dockerfile +7 -0
  20. package/nodenithy/build/trustedzone/Dockerfile.tmpl +57 -0
  21. package/nodenithy/build/trustedzone/scripts/binary-fs-build.sh +22 -0
  22. package/nodenithy/build/trustedzone/src/.env +3 -0
  23. package/nodenithy/build/trustedzone/src/etny_crypto.js +202 -0
  24. package/nodenithy/build/trustedzone/src/etny_exec.js +54 -0
  25. package/nodenithy/build/trustedzone/src/image_registry_abi.js +808 -0
  26. package/nodenithy/build/trustedzone/src/models.js +261 -0
  27. package/nodenithy/build/trustedzone/src/package.json +40 -0
  28. package/nodenithy/build/trustedzone/src/pox_abi.js +1491 -0
  29. package/nodenithy/build/trustedzone/src/swift_stream_service.js +147 -0
  30. package/nodenithy/build/trustedzone/src/task_status.js +15 -0
  31. package/nodenithy/build/trustedzone/src/test.js +44 -0
  32. package/nodenithy/build/trustedzone/src/trustedzone.js.tmpl +508 -0
  33. package/nodenithy/build/trustedzone/src/wallet.js +28 -0
  34. package/nodenithy/build/validator/Dockerfile +58 -0
  35. package/nodenithy/build/validator/package-lock.json +6 -0
  36. package/nodenithy/build/validator/scripts/binary-fs-build.sh +19 -0
  37. package/nodenithy/build/validator/src/.env +3 -0
  38. package/nodenithy/build/validator/src/cert.pem +5 -0
  39. package/nodenithy/build/validator/src/etny_crypto.js +204 -0
  40. package/nodenithy/build/validator/src/etny_exec.js +52 -0
  41. package/nodenithy/build/validator/src/image_registry_abi.js +808 -0
  42. package/nodenithy/build/validator/src/key.pem +6 -0
  43. package/nodenithy/build/validator/src/models.js +261 -0
  44. package/nodenithy/build/validator/src/package-lock.json +2498 -0
  45. package/nodenithy/build/validator/src/package.json +40 -0
  46. package/nodenithy/build/validator/src/pox_abi.js +1491 -0
  47. package/nodenithy/build/validator/src/swift_stream_service.js +147 -0
  48. package/nodenithy/build/validator/src/task_status.js +15 -0
  49. package/nodenithy/build/validator/src/test.js +44 -0
  50. package/nodenithy/build/validator/src/trustedzone.js +613 -0
  51. package/nodenithy/build/validator/src/validator_abi.js +834 -0
  52. package/nodenithy/build/validator/src/wallet.js +28 -0
  53. package/nodenithy/build.js +184 -0
  54. package/nodenithy/build.mjs +179 -0
  55. package/nodenithy/build.sh +161 -0
  56. package/nodenithy/ipfs.js +135 -0
  57. package/nodenithy/ipfs.mjs +551 -0
  58. package/nodenithy/public/favicon.ico +0 -0
  59. package/nodenithy/public/index.html +43 -0
  60. package/nodenithy/public/logo192.png +0 -0
  61. package/nodenithy/public/logo512.png +0 -0
  62. package/nodenithy/public/manifest.json +25 -0
  63. package/nodenithy/public/robots.txt +3 -0
  64. package/nodenithy/run/__pycache__/swift_stream_service.cpython-312.pyc +0 -0
  65. package/nodenithy/run/app/input.txt +4 -0
  66. package/nodenithy/run/app/payload.js +4 -0
  67. package/nodenithy/run/docker-compose-final.yml.tmpl +65 -0
  68. package/nodenithy/run/docker-compose-swift-stream.yml +17 -0
  69. package/nodenithy/run/docker-compose.yml.tmpl +76 -0
  70. package/nodenithy/run/etny-securelock-test.yaml.tpl +46 -0
  71. package/nodenithy/run/etny-trustedzone-test.yaml.tpl +45 -0
  72. package/nodenithy/run/git.sh +22 -0
  73. package/nodenithy/run/image_registry.abi +1 -0
  74. package/nodenithy/run/image_registry.js +372 -0
  75. package/nodenithy/run/image_registry.py +327 -0
  76. package/nodenithy/run/image_registry_runner.py +71 -0
  77. package/nodenithy/run/ipfs.sh +58 -0
  78. package/nodenithy/run/ipfs_pre.sh +75 -0
  79. package/nodenithy/run/public_key_service.js +90 -0
  80. package/nodenithy/run/public_key_service.py +107 -0
  81. package/nodenithy/run/swift_stream_service.py +212 -0
  82. package/nodenithy/run/swiftstream.py +37 -0
  83. package/nodenithy/run/swiftstream1.py +27 -0
  84. package/nodenithy/run.js +538 -0
  85. package/nodenithy/run.sh +277 -0
  86. package/nodenithy/scripts/build-ipfs-upload.sh +23 -0
  87. package/nodenithy/scripts/build.sh +40 -0
  88. package/nodenithy/scripts/ipfs-daemon.sh +7 -0
  89. package/nodenithy/scripts/run.sh +50 -0
  90. package/nodenithy/src/App.css +57 -0
  91. package/nodenithy/src/ec_helloworld_example.js +64 -0
  92. package/nodenithy/src/index.css +13 -0
  93. package/nodenithy/src/index.js +17 -0
  94. package/nodenithy/src/preStart.js +45 -0
  95. package/nodenithy/src/preStart.mjs +57 -0
  96. package/nodenithy/src/reportWebVitals.js +13 -0
  97. package/nodenithy/src/serverless/backend.js +5 -0
  98. package/package.json +48 -0
  99. package/postinstall.js +34 -0
  100. package/publish.js +126 -0
  101. package/pynithy/build/docker-compose.yml +68 -0
  102. package/pynithy/build/las/Dockerfile +11 -0
  103. package/pynithy/build/las/src/etny_entrypoint.sh +6 -0
  104. package/pynithy/build/las/src/las_entrypoint.sh +26 -0
  105. package/pynithy/build/scripts/binary-fs-build.sh +28 -0
  106. package/pynithy/build/securelock/Dockerfile.tmpl +78 -0
  107. package/pynithy/build/securelock/scripts/binary-fs-build.sh +41 -0
  108. package/pynithy/build/securelock/src/app/.env +5 -0
  109. package/pynithy/build/securelock/src/app/cert1-ca1-clean.crt +10 -0
  110. package/pynithy/build/securelock/src/app/cert1-ca1-clean.key +6 -0
  111. package/pynithy/build/securelock/src/app/enclave_pub_cert.pem +10 -0
  112. package/pynithy/build/securelock/src/app/input.txt +1 -0
  113. package/pynithy/build/securelock/src/app/payload.py +25 -0
  114. package/pynithy/build/securelock/src/app/public-cert-clean.pem +10 -0
  115. package/pynithy/build/securelock/src/app/result.txt +1 -0
  116. package/pynithy/build/securelock/src/app/transaction.txt +1 -0
  117. package/pynithy/build/securelock/src/etny_crypto.py +167 -0
  118. package/pynithy/build/securelock/src/etny_exec.py +79 -0
  119. package/pynithy/build/securelock/src/image_registry.abi +1 -0
  120. package/pynithy/build/securelock/src/key_generation.py +17 -0
  121. package/pynithy/build/securelock/src/models.py +176 -0
  122. package/pynithy/build/securelock/src/pox.abi +1489 -0
  123. package/pynithy/build/securelock/src/securelock.py.tmpl +411 -0
  124. package/pynithy/build/securelock/src/swift_stream_service.py +186 -0
  125. package/pynithy/build/trustedzone/Dockerfile.tmpl +56 -0
  126. package/pynithy/build/trustedzone/scripts/binary-fs-build.sh +32 -0
  127. package/pynithy/build/trustedzone/src/app/.env +5 -0
  128. package/pynithy/build/trustedzone/src/app/cert1-ca1-clean.crt +10 -0
  129. package/pynithy/build/trustedzone/src/app/cert1-ca1-clean.key +6 -0
  130. package/pynithy/build/trustedzone/src/app/enclave_pub_cert.pem +10 -0
  131. package/pynithy/build/trustedzone/src/app/input.txt +1 -0
  132. package/pynithy/build/trustedzone/src/app/payload.py +25 -0
  133. package/pynithy/build/trustedzone/src/app/public-cert-clean.pem +10 -0
  134. package/pynithy/build/trustedzone/src/app/result.txt +1 -0
  135. package/pynithy/build/trustedzone/src/app/securelock.crt +10 -0
  136. package/pynithy/build/trustedzone/src/app/transaction.txt +1 -0
  137. package/pynithy/build/trustedzone/src/app/trustedzone.crt +10 -0
  138. package/pynithy/build/trustedzone/src/etny_crypto.py +188 -0
  139. package/pynithy/build/trustedzone/src/etny_exec.py +56 -0
  140. package/pynithy/build/trustedzone/src/formatter.py +42 -0
  141. package/pynithy/build/trustedzone/src/image_registry.abi +1 -0
  142. package/pynithy/build/trustedzone/src/key_generation.py +17 -0
  143. package/pynithy/build/trustedzone/src/models.py +176 -0
  144. package/pynithy/build/trustedzone/src/pox.abi +1489 -0
  145. package/pynithy/build/trustedzone/src/swift_stream_service.py +186 -0
  146. package/pynithy/build/trustedzone/src/trustedzone.py.tmpl +460 -0
  147. package/pynithy/build.mjs +179 -0
  148. package/pynithy/docker-compose.yml +0 -0
  149. package/pynithy/ipfs.mjs +244 -0
  150. package/pynithy/public/favicon.ico +0 -0
  151. package/pynithy/public/index.html +43 -0
  152. package/pynithy/public/logo192.png +0 -0
  153. package/pynithy/public/logo512.png +0 -0
  154. package/pynithy/public/manifest.json +25 -0
  155. package/pynithy/public/robots.txt +3 -0
  156. package/pynithy/run/certs/cert.pem +31 -0
  157. package/pynithy/run/certs/challenge.crt +10 -0
  158. package/pynithy/run/certs/key.pem +52 -0
  159. package/pynithy/run/docker-compose-final.yml +59 -0
  160. package/pynithy/run/docker-compose-final.yml.tmpl +59 -0
  161. package/pynithy/run/docker-compose-swift-stream.yml +27 -0
  162. package/pynithy/run/docker-compose-swift-stream.yml.tmpl +27 -0
  163. package/pynithy/run/docker-compose.yml +55 -0
  164. package/pynithy/run/docker-compose.yml.tmpl +55 -0
  165. package/pynithy/run/etny-pynity-test.yaml.tpl +46 -0
  166. package/pynithy/run/etny-securelock-test.yaml.tpl +46 -0
  167. package/pynithy/run/etny-trustedzone-test.yaml.tpl +46 -0
  168. package/pynithy/run/git.sh +22 -0
  169. package/pynithy/run/image_registry.abi +1 -0
  170. package/pynithy/run/image_registry.js +372 -0
  171. package/pynithy/run/image_registry.py +139 -0
  172. package/pynithy/run/image_registry_runner.py +45 -0
  173. package/pynithy/run/ipfs.sh +89 -0
  174. package/pynithy/run/public_key_service.js +90 -0
  175. package/pynithy/run/swiftstream.py +28 -0
  176. package/pynithy/run.js +538 -0
  177. package/pynithy/src/App.css +57 -0
  178. package/pynithy/src/ec_helloworld_example.js +64 -0
  179. package/pynithy/src/index.css +13 -0
  180. package/pynithy/src/index.js +17 -0
  181. package/pynithy/src/preStart.mjs +57 -0
  182. package/pynithy/src/reportWebVitals.js +13 -0
  183. package/pynithy/src/serverless/__init__.py +0 -0
  184. package/pynithy/src/serverless/backend.py +2 -0
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/python
2
+
3
+ # update 29.12.2022
4
+ import binascii
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import string
9
+ import random
10
+ import io
11
+ import time
12
+
13
+ from etny_crypto import etny_crypto as crypto
14
+ from web3 import Web3
15
+ from eth_account import Account
16
+ from web3.middleware import geth_poa_middleware
17
+ from key_generation import get_wallet_address
18
+ from etny_exec import execute_task, TaskStatus
19
+ from models import *
20
+ from swift_stream_service import SwiftStreamService
21
+ from eth_account.messages import defunct_hash_message
22
+
23
+
24
+ # todo: remove EtnyResultPoc.debug
25
+ class EtnySecureLock:
26
+ debug = False
27
+
28
+ def __init__(self, swiftStreamClient):
29
+ self.swift_stream_service = swiftStreamClient
30
+ self.version = 'v3'
31
+ print(f'ETNY Pynithy [{self.version}]')
32
+ self.__set_initializers()
33
+ self.save_pub_cert()
34
+ self.__load_env()
35
+ # self.read_client_challenge()
36
+ # self.generate_challenge()
37
+ # self.generate_eth_compatible_wallet()
38
+ # print('wallet = ', self.publickey)
39
+ # print('private = ', self.privatekey)
40
+ self.read_contract_abi()
41
+ self.init_web3()
42
+ self.print_env()
43
+ # if not EtnySecureLock.debug:
44
+ # self.reset_cert_file()
45
+
46
+ @staticmethod
47
+ def read_env(env_file):
48
+ with open(env_file, 'r') as f:
49
+ # Read each line of the file
50
+ for line in f:
51
+ # Split the line at the first '=' character
52
+ key, value = line.split('=', 1)
53
+ # Set the environment variable
54
+ os.environ[key] = value
55
+
56
+ @staticmethod
57
+ def read_env_str(env_str):
58
+ with io.StringIO(env_str) as f:
59
+ # Read each line of the string
60
+ for line in f:
61
+ # Split the line at the first '=' character
62
+ key, value = line.split('=', 1)
63
+ # Set the environment variable and remove new line
64
+ os.environ[key] = re.sub(r'\n', '', value)
65
+
66
+ def __extract_signer(self, checksum, signature):
67
+ signer = self.w3.eth.account.recoverHash(defunct_hash_message(text=checksum), signature=signature)
68
+ return signer
69
+
70
+ def __set_initializers(self):
71
+ self.is_valid_client_data = True
72
+ self.key_file = "/private/__ENCLAVE_NAME_SECURELOCK__/key.pem"
73
+ self.cert_file = "/app/__ENCLAVE_NAME_SECURELOCK__/cert.pem"
74
+ self.pub_cert_file = "/app/__ENCLAVE_NAME_SECURELOCK__/enclave_pub_cert.pem"
75
+ self.payload = 'payload.etny.securelock'
76
+ self.input = 'input.txt.securelock'
77
+ self.result_file = '/app/result.txt'
78
+ self.transaction_file = '/app/transaction.txt'
79
+ self.smart_contract_address = '__SMART_CONTRACT_ADDRESS__'
80
+ self.image_registry_address = '__IMAGE_REGISTRY_ADDRESS__'
81
+ self.chain_id = __CHAIN_ID__
82
+ self.web3_provider = '__RPC_URL__'
83
+ self.etny_bucket = "__BUCKET_NAME__"
84
+ self.trusted_zone_public_key = ''
85
+ if EtnySecureLock.debug:
86
+ self.key_file = "./app/cert1-ca1-clean.key"
87
+ self.cert_file = "./app/cert1-ca1-clean.crt"
88
+ self.payload = 'payload.py'
89
+ self.input = 'input.txt'
90
+ self.result_file = './app/result.txt'
91
+ self.transaction_file = './app/transaction.txt'
92
+ self.pub_cert_file = "./app/enclave_pub_cert.pem"
93
+ # self.trustedzone_public_key = "./app/enclave_pub_cert.pem"
94
+
95
+ def validate_client_payload(self, payload_data, input_data):
96
+ self.get_do_request_metadata()
97
+ if self._metadata.payload_metadata_obj.checksum is not None:
98
+ #print('Computing payload checksum: ')
99
+ payload_checksum = self.compute_sha256_checksum(payload_data)
100
+ #print('payload checksum: ', payload_checksum)
101
+ # check the wallet address that signed payload checksum is the one from order metadata
102
+ payload_signer = self.__extract_signer(payload_checksum, self._metadata.payload_metadata_obj.checksum)
103
+ if payload_signer.lower() != self.order_metadata.do_owner.lower():
104
+ self.task_code = TaskStatus.PAYLOAD_CHECKSUM_ERROR
105
+ self.task_result = 'PAYLOAD CHECKSUM DOESN\'T MATCH'
106
+ self.is_valid_client_data = False
107
+ return
108
+
109
+ if self._metadata.input_metadata_obj.checksum is not None:
110
+ input_checksum = self.compute_sha256_checksum(input_data)
111
+ #print('input checksum: ', input_checksum)
112
+ # check the wallet address that signed input checksum is the one from order metadata
113
+ input_signer = self.__extract_signer(input_checksum, self._metadata.input_metadata_obj.checksum)
114
+ if input_signer.lower() != self.order_metadata.do_owner.lower():
115
+ self.task_code = TaskStatus.INPUT_CHECKSUM_ERROR
116
+ self.task_result = 'INPUT CHECKSUM DOESN\'T MATCH'
117
+ self.is_valid_client_data = False
118
+ return
119
+
120
+ def wait_for_payload_and_input(self):
121
+ print('Waiting for payload and input')
122
+ self.wait_for_trustedzone(self.etny_bucket, self.payload)
123
+ self.wait_for_trustedzone(self.etny_bucket, self.input)
124
+
125
+ def wait_for_trustedzone(self, bucket_name, object_name, timeout=3600):
126
+ i = 0
127
+ print(f'Checking if object {object_name} exists in bucket {bucket_name}')
128
+ while True:
129
+ time.sleep(1)
130
+ i = i + 1
131
+ if i > timeout:
132
+ break
133
+ (status, result) = self.swift_stream_service.is_object_in_bucket(bucket_name, object_name)
134
+ if status:
135
+ break
136
+
137
+ print('secure lock finished the execution')
138
+
139
+ def get_do_request_metadata(self):
140
+ order = Order(self.etny.caller()._getOrder(self.order_id), self.order_id)
141
+ #print('order', order)
142
+ self._metadata = DOReqMetadata(self.etny.caller()._getDORequestMetadata(order.do_req), order.do_req)
143
+ self.order_metadata = order
144
+ #print('metadata', self._metadata)
145
+
146
+ def compute_sha256_checksum(self, file_data):
147
+ if type(file_data) is str:
148
+ file_data = file_data.encode('utf-8')
149
+
150
+ return hashlib.sha256(file_data).hexdigest()
151
+
152
+ # h = hashlib.sha256()
153
+ # file = io.BytesIO(file_data)
154
+ # while True:
155
+ # Reading is buffered, so we can read smaller chunks.
156
+ # chunk = file.read(h.block_size)
157
+ # if not chunk:
158
+ # break
159
+ # h.update(chunk)
160
+ # return h.hexdigest()
161
+
162
+ def reset_cert_file(self):
163
+ #print('Resetting the cert file')
164
+ try:
165
+ with open(self.key_file, 'r+') as f:
166
+ f.truncate(0)
167
+ except Exception as e:
168
+ print('Error while removing the private key file content', e)
169
+
170
+ #with open(self.key_file, 'r') as f:
171
+ # print('cert file content', f.read(), '##################')
172
+
173
+ def generate_eth_compatible_wallet(self):
174
+ decrypted_string = crypto.decrypt(
175
+ private_key_file=self.key_file,
176
+ encrypted_msg=self.encrypted_tuple
177
+ )
178
+ #print('decrypted_string = ', decrypted_string)
179
+ (public, private) = get_wallet_address(decrypted_string.decode(), self.enclave_challenge)
180
+ self.publickey = public
181
+ self.privatekey = private
182
+
183
+ def print_env(self):
184
+ print('chain id:', self.chain_id)
185
+ print('smart contract address:', self.smart_contract_address)
186
+ print('web3 provider:', self.web3_provider)
187
+ print('encrypted challenge:', self.client_challenge)
188
+ print('order id:', self.order_id)
189
+
190
+ def init_web3(self):
191
+ self.w3 = Web3(Web3.HTTPProvider(self.web3_provider))
192
+ self.w3.middleware_onion.inject(geth_poa_middleware, layer=0)
193
+
194
+ # self.acct = Account.privateKeyToAccount(self.privatekey)
195
+ self.etny = self.w3.eth.contract(address=self.w3.toChecksumAddress(self.smart_contract_address),
196
+ abi=self.contract_abi)
197
+ self.image_registry = self.w3.eth.contract(address=self.w3.toChecksumAddress(self.image_registry_address),
198
+ abi=self.image_registry_abi)
199
+
200
+ def read_contract_abi(self):
201
+ self.contract_abi = self.__read_contract_abi('pox.abi')
202
+ self.image_registry_abi = self.__read_contract_abi('image_registry.abi')
203
+
204
+ def __read_contract_abi(self, contract_name):
205
+ f = open(os.path.dirname(os.path.realpath(__file__)) + f'/{contract_name}')
206
+ contract_abi = f.read()
207
+ f.close()
208
+ return contract_abi
209
+
210
+ def __load_env(self):
211
+ if os.getenv('ETNY_CHAIN_ID') is not None:
212
+ self.chain_id = int(os.getenv('ETNY_CHAIN_ID'))
213
+
214
+ if os.getenv('ETNY_SMART_CONTRACT_ADDRESS') is not None:
215
+ self.smart_contract_address = os.getenv('ETNY_SMART_CONTRACT_ADDRESS').rstrip()
216
+
217
+ if os.getenv('ETNY_WEB3_PROVIDER') is not None:
218
+ self.web3_provider = os.getenv('ETNY_WEB3_PROVIDER').rstrip()
219
+
220
+ self.client_challenge = os.getenv('ETNY_CLIENT_CHALLENGE')
221
+ self.order_id = int(os.getenv('ETNY_ORDER_ID'))
222
+
223
+ def read_client_challenge(self):
224
+ self.encrypted_tuple = crypto.encrypted_data_from_base64_json(self.client_challenge)
225
+
226
+ def generate_challenge(self, length=20):
227
+ lowercase_only = ''.join(
228
+ random.choice(string.ascii_lowercase) for _ in range(length)
229
+ )
230
+ #print('random challenge:', lowercase_only)
231
+ self.enclave_challenge = lowercase_only
232
+ return self.enclave_challenge
233
+
234
+ def build_result(self):
235
+ self.result = (f'{self.version}:{self.task_code}:{self.task_result_checksum}:{self.enclave_challenge}:')
236
+
237
+ def addResult(self):
238
+ self.build_result()
239
+ print(f'adding result to order {self.order_id}')
240
+ nonce = self.w3.eth.getTransactionCount(self.publickey)
241
+ unicorn_txn = self.etny.functions._addResultToOrder(
242
+ self.order_id, self.result
243
+ ).buildTransaction({
244
+ 'gas': 1000000,
245
+ 'chainId': self.chain_id,
246
+ 'nonce': nonce,
247
+ 'gasPrice': self.w3.toWei("1", "mwei"),
248
+ })
249
+
250
+ signed_txn = self.w3.eth.account.sign_transaction(unicorn_txn, private_key=self.acct.key)
251
+ self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)
252
+ # self.transaction = unicorn_tx signed
253
+ hash = self.w3.toHex(self.w3.sha3(signed_txn.rawTransaction))
254
+
255
+ try:
256
+ receipt = self.w3.eth.waitForTransactionReceipt(hash)
257
+ except Exception as e:
258
+ print(f'An error occurred while sending transaction result {self.order_id}: ', e)
259
+ raise
260
+
261
+ #print('transaction status: ', receipt.status)
262
+ #print('transaction receipt: ', receipt)
263
+ if receipt.status == 1:
264
+ print("Result transaction was successful!")
265
+ else:
266
+ print("Result transaction was UNSUCCESSFUL!")
267
+
268
+ #print("Result payload: %s" % self.result)
269
+ #print("TX Raw: %s" % signed_txn.rawTransaction)
270
+ #print("TX Hash: %s" % hash)
271
+
272
+ def build_transaction(self):
273
+ self.build_result()
274
+ print(f'adding result to order {self.order_id}')
275
+ nonce = self.w3.eth.getTransactionCount(self.publickey)
276
+ unicorn_txn = self.etny.functions._addResultToOrder(
277
+ self.order_id, self.result
278
+ ).buildTransaction({
279
+ 'gas': 1000000,
280
+ 'chainId': self.chain_id,
281
+ 'nonce': nonce,
282
+ 'gasPrice': self.w3.toWei("1", "mwei"),
283
+ })
284
+
285
+ signed_txn = self.w3.eth.account.sign_transaction(unicorn_txn, private_key=self.acct.key)
286
+ signed_tx_as_bytes = binascii.hexlify(signed_txn.rawTransaction)
287
+ self.signed_tx_as_bytes = signed_tx_as_bytes
288
+
289
+ def get_result_checksum(self):
290
+ self.task_result_checksum = hashlib.sha256(self.task_result.encode("utf-8")).hexdigest()
291
+
292
+ def save_result(self):
293
+ self.__get_latest_trusted_zone_public_key()
294
+ self.encrypt_file_and_push_to_swifstream(str(self.task_result), "result.txt")
295
+ self.encrypt_file_and_push_to_swifstream(str(self.task_code), "result_code.txt")
296
+
297
+ def save_pub_cert(self):
298
+ self.swift_stream_service.create_bucket(self.etny_bucket)
299
+ self.swift_stream_service.put_file_content(self.etny_bucket,
300
+ "cert.pem",
301
+ self.cert_file)
302
+
303
+ def save_transaction(self):
304
+ self.swift_stream_service.create_bucket(self.etny_bucket)
305
+ transaction = io.BytesIO(self.signed_tx_as_bytes)
306
+ self.swift_stream_service.put_file_content(self.etny_bucket,
307
+ "transaction.txt",
308
+ self.transaction_file,
309
+ transaction)
310
+
311
+ def execute(self):
312
+ payload_data = self.__get_file_content_and_decrypt(self.payload)
313
+ input_data = self.__get_file_content_and_decrypt(self.input)
314
+ print('Validate client payload and input')
315
+ self.validate_client_payload(payload_data, input_data)
316
+ if app.is_valid_client_data:
317
+ print('Client payload and input are valid')
318
+ else:
319
+ print('Client payload and input are NOT valid')
320
+ return
321
+
322
+ task_result = execute_task(payload_data, input_data)
323
+ print('TASK RESULT (code, data):', task_result)
324
+ self.task_code = str(task_result[0])
325
+ self.task_result = task_result[1]
326
+
327
+ def __get_file_content_and_decrypt(self, object_name):
328
+ status, encrypted_base64 = self.swift_stream_service.get_file_content(self.etny_bucket, object_name)
329
+ if not status:
330
+ print(f'Failed to get {object_name} file')
331
+ raise Exception(f'Failed to get {object_name} file')
332
+
333
+ encrypted_tuple = crypto.encrypted_data_from_base64_json(encrypted_base64.encode('utf-8'))
334
+ decrypted_result = crypto.decrypt(self.key_file, encrypted_tuple)
335
+ return decrypted_result.decode('utf-8')
336
+
337
+ def encrypt_file_and_push_to_swifstream(self, file_data, file_name):
338
+ encrypted_input = crypto.encrypt_with_pub_key(self.trusted_zone_public_key, file_data.encode('utf-8'))
339
+ encrypted_input_base64 = crypto.encrypted_data_to_base64_json(encrypted_input)
340
+
341
+ # file name should end with secure lock '.securelock' extension
342
+ file_name = file_name + '.securelock'
343
+ self.swift_stream_service.create_bucket(self.etny_bucket)
344
+ data = io.BytesIO(encrypted_input_base64)
345
+ status, _ = self.swift_stream_service.put_file_content(self.etny_bucket,
346
+ file_name,
347
+ "",
348
+ data)
349
+ if status:
350
+ print(f'File {file_name} encrypted and saved to swift stream successfully')
351
+
352
+ def __get_trusted_zone_public_key(self):
353
+ print('getting the public key of the trusted zone enclave')
354
+ image_hash = self._metadata.image_hash
355
+ if EtnySecureLock.debug:
356
+ image_hash = 'v3-hash-1'
357
+ self.trusted_zone_public_key = self.image_registry.caller().getTrustedZoneImageCertPublicKey(
358
+ image_hash)
359
+
360
+ def __get_latest_trusted_zone_public_key(self):
361
+ print('getting latest public key of the trusted zone enclave')
362
+ self.trusted_zone_public_key = self.image_registry.caller().getLatestTrustedZoneImageCertPublicKey(
363
+ '__TRUSTED_ZONE_IMAGE__', 'v3')[1]
364
+
365
+
366
+ if __name__ == '__main__':
367
+ print('[SecureLock] Loading env variables..')
368
+ try:
369
+ if EtnySecureLock.debug:
370
+ swiftStreamClient = SwiftStreamService("localhost:9000",
371
+ "swiftstreamadmin",
372
+ "swiftstreamadmin")
373
+ else:
374
+ swiftStreamClient = SwiftStreamService("etny-swift-stream:9000",
375
+ "swiftstreamadmin",
376
+ "swiftstreamadmin")
377
+
378
+ status, env_content = swiftStreamClient.get_file_content("etny-pynithy-testnet-v3", ".env")
379
+ if not status:
380
+ print("Failed to get .env file")
381
+ raise Exception("Failed to get .env file")
382
+ EtnySecureLock.read_env_str(env_content)
383
+ except:
384
+ cert_file = "/app/__ENCLAVE_NAME_SECURELOCK__/cert.pem"
385
+ with open(cert_file, 'r') as f:
386
+ print("PUBLIC_CERT:", f.read())
387
+ exit(1)
388
+
389
+ if not EtnySecureLock.debug:
390
+ with open("/app/__ENCLAVE_NAME_SECURELOCK__/cert.pem", 'r') as f:
391
+ print("PUBLIC_CERT:", f.read())
392
+
393
+ print('Initializing..')
394
+ app = EtnySecureLock(swiftStreamClient)
395
+ print('Validate client payload and input')
396
+ app.wait_for_payload_and_input()
397
+
398
+ if app.is_valid_client_data:
399
+ print('Executing client code..')
400
+ app.execute()
401
+ else:
402
+ print('Failed client payload and input validation')
403
+ # print('Generating task result checksum..')
404
+ # app.get_result_checksum()
405
+ # print('Building transaction..')
406
+ # app.build_transaction()
407
+ # print('Saving transaction...')
408
+ # app.save_transaction()
409
+ # print('Saving the result..')
410
+ app.save_result()
411
+ print('Finished the execution')
@@ -0,0 +1,186 @@
1
+ import os
2
+
3
+ from minio import Minio
4
+ from minio.error import S3Error
5
+
6
+
7
+ class SwiftStreamService:
8
+
9
+ def __init__(self, endpoint: str, access_key: str, secret_key: str):
10
+ self.client = Minio(endpoint=endpoint,
11
+ access_key=access_key,
12
+ secret_key=secret_key,
13
+ secure=False)
14
+
15
+ def create_bucket(self, bucket_name: str) -> (bool, str):
16
+ try:
17
+ if not self.client.bucket_exists(bucket_name):
18
+ self.client.make_bucket(bucket_name)
19
+ else:
20
+ return False, f"Bucket, {bucket_name} already exists!"
21
+ except S3Error as err:
22
+ return False, err
23
+
24
+ return True, f"Bucket, {bucket_name} successfully created!"
25
+
26
+ def delete_bucket(self, bucket_name: str) -> (bool, str):
27
+ try:
28
+ if self.client.bucket_exists(bucket_name):
29
+ file_objects = self.client.list_objects(bucket_name)
30
+ if file_objects.size() == 0:
31
+ self.client.remove_bucket(bucket_name)
32
+ else:
33
+ for file_object in file_objects:
34
+ self.delete_file(bucket_name, file_object)
35
+ self.client.remove_bucket(bucket_name)
36
+ else:
37
+ return False, f"Bucket, {bucket_name} does not exists!"
38
+ except S3Error as err:
39
+ return False, err
40
+
41
+ return True, f"Bucket, {bucket_name} successfully deleted!"
42
+
43
+ def delete_file(self, bucket_name: str, file_name: str) -> (bool, str):
44
+ try:
45
+ self.client.remove_object(bucket_name, file_name)
46
+ except S3Error as err:
47
+ return False, err
48
+
49
+ return True, f"File, {file_name} successfully deleted!"
50
+
51
+ def delete_files(self, bucket_name: str, list_of_files: list[str]) -> (bool, str):
52
+ try:
53
+ errors = self.client.remove_objects(bucket_name, list_of_files)
54
+ for error in errors:
55
+ print(f"[Error] Error occurred when deleting file: {error}!")
56
+ except S3Error as err:
57
+ return False, err
58
+
59
+ return True, f"Files, {list_of_files} successfully deleted!"
60
+
61
+ def upload_file(self, bucket_name: str, file_name: str, file_path: str) -> (bool, str):
62
+ try:
63
+ if self.client.bucket_exists(bucket_name):
64
+ self.client.fput_object(bucket_name, file_name, file_path)
65
+ else:
66
+ self.create_bucket(bucket_name)
67
+ self.client.fput_object(bucket_name, file_name, file_path)
68
+ except S3Error as err:
69
+ return False, err
70
+
71
+ return True, f"{file_path} is successfully uploaded to bucket {bucket_name}."
72
+
73
+ def upload_files(self, bucket_name: str, list_of_files: list[str],
74
+ upload_file_paths: list[str]) -> (bool, str):
75
+ try:
76
+ if self.client.bucket_exists(bucket_name):
77
+ for file_idx in range(len(upload_file_paths)):
78
+ self.client.fput_object(bucket_name,
79
+ list_of_files[file_idx],
80
+ upload_file_paths[file_idx])
81
+ else:
82
+ self.create_bucket(bucket_name)
83
+ for file_idx in range(len(upload_file_paths)):
84
+ self.client.fput_object(bucket_name,
85
+ list_of_files[file_idx],
86
+ upload_file_paths[file_idx])
87
+ except S3Error as err:
88
+ return False, err
89
+
90
+ return True, f"{upload_file_paths} are successfully uploaded to bucket {bucket_name}."
91
+
92
+ def download_file(self, bucket_name: str, file_name: str, file_path: str) -> (bool, str):
93
+ try:
94
+ if self.client.bucket_exists(bucket_name):
95
+ self.client.fget_object(bucket_name, file_name, file_path)
96
+ else:
97
+ return False, f"Bucket, {bucket_name} does not exists!"
98
+ except S3Error as err:
99
+ return False, err
100
+
101
+ return True, f"File, {file_name} from bucket {bucket_name} was downloaded in {file_path}."
102
+
103
+ def download_files(self, bucket_name: str, list_of_files: list[str],
104
+ download_file_paths: list[str]) -> (bool, str):
105
+ try:
106
+ if self.client.bucket_exists(bucket_name):
107
+ for file_idx in range(len(list_of_files)):
108
+ self.client.fget_object(bucket_name,
109
+ list_of_files[file_idx],
110
+ download_file_paths[file_idx])
111
+ else:
112
+ return False, f"Bucket, {bucket_name} does not exists!"
113
+ except S3Error as err:
114
+ return False, err
115
+
116
+ return True, f"{download_file_paths} are successfully uploaded to bucket {bucket_name}."
117
+
118
+ def get_file_content_bytes(self, bucket_name: str, file_name: str) -> (bool, bytes):
119
+ response = None
120
+ try:
121
+ response = self.client.get_object(bucket_name, file_name)
122
+ _d = b''
123
+ for data in response.stream(amt=1024 * 1024):
124
+ _d = _d + data
125
+
126
+ except S3Error as err:
127
+ return False, err
128
+ finally:
129
+ if response is not None:
130
+ response.close()
131
+ response.release_conn()
132
+ return True, _d
133
+
134
+ def get_file_content(self, bucket_name: str, file_name: str) -> (bool, str):
135
+ status, content = self.get_file_content_bytes(bucket_name, file_name)
136
+ if status:
137
+ return True, content.decode('utf-8')
138
+ return status, content
139
+
140
+ def put_file_content(self, bucket_name: str, object_name: str, object_path: str,
141
+ object_data: object = None) -> (bool, str):
142
+ try:
143
+ if object_data is not None:
144
+ self.client.put_object(bucket_name,
145
+ object_name,
146
+ object_data,
147
+ len(object_data.getbuffer()))
148
+ else:
149
+ object_stat = os.stat(object_path)
150
+ with open(object_path, 'rb') as file_data:
151
+ self.client.put_object(bucket_name,
152
+ object_name,
153
+ file_data,
154
+ object_stat.st_size)
155
+ file_data.close()
156
+ except S3Error as err:
157
+ return False, err
158
+
159
+ return True, f"{object_name} is successfully uploaded to bucket {bucket_name}."
160
+
161
+ def is_object_in_bucket(self, bucket_name: str, object_name: str) -> (bool, str):
162
+ found = False
163
+ try:
164
+ result = self.client.stat_object(bucket_name, object_name)
165
+ if result:
166
+ found = True
167
+ except S3Error as err:
168
+ return False, err
169
+
170
+ if found:
171
+ return found, f"{object_name} exists inside {bucket_name}."
172
+ else:
173
+ return found, f"{object_name} doesn't exists inside {bucket_name}."
174
+
175
+ def _list_buckets(self) -> None:
176
+ buckets = self.client.list_buckets()
177
+ for bucket in buckets:
178
+ print(bucket.name, bucket.creation_date)
179
+
180
+ def _list_objects(self, bucket_name: str) -> None:
181
+ objects = self.client.list_objects(bucket_name)
182
+ for obj in objects:
183
+ print("-> ", obj.object_name, obj.owner_name)
184
+
185
+ def _is_bucket(self, bucket_name: str) -> bool:
186
+ return self.client.bucket_exists(bucket_name)
@@ -0,0 +1,56 @@
1
+ FROM registry.scontain.com:5050/sconecuratedimages/apps:python3.10.5-alpine3.15-scone5.8-pre-release as release
2
+
3
+ RUN apk update
4
+
5
+ RUN cd /
6
+ RUN apk add bash openrc bind-tools sudo npm binutils
7
+ RUN pip3 install --upgrade pip
8
+ RUN pip3 install --upgrade setuptools
9
+ RUN pip3 install python-dotenv
10
+ RUN pip3 install web3==5.31.0
11
+ RUN pip3 install cryptography==42.0.7
12
+ RUN pip3 install ecdsa
13
+ RUN pip3 install pyasn1
14
+ RUN pip3 install tinyec
15
+ RUN pip3 install pyinstaller
16
+ RUN pip3 install minio
17
+ RUN pip3 install pynacl
18
+
19
+
20
+ ENV ENCLAVE_NAME_TRUSTEDZONE=__ENCLAVE_NAME_TRUSTEDZONE__
21
+
22
+ RUN mkdir binary-fs-dir
23
+
24
+ COPY src/* /etny-trustedzone/
25
+ COPY ./scripts/* /etny-trustedzone/
26
+
27
+ RUN etny-trustedzone/binary-fs-build.sh
28
+
29
+ FROM registry.scontain.com:5050/sconecuratedimages/crosscompilers as build
30
+
31
+ COPY --from=release /binary-fs-dir /.
32
+
33
+ RUN scone gcc ./binary_fs_blob.s ./libbinary_fs_template.a -shared -o /libbinary-fs.so
34
+
35
+ FROM registry.scontain.com:5050/sconecuratedimages/apps:python3.10.5-alpine3.15-scone5.8-pre-release
36
+
37
+ COPY --from=build /usr/local/bin/scone /usr/local/bin/scone
38
+
39
+ #RUN scone cas attest scone-cas.cf 3061b9feb7fa67f3815336a085f629a13f04b0a1667c93b14ff35581dc8271e4 -GCS --only_for_testing-debug --only_for_testing-ignore-signer
40
+
41
+ COPY --from=build /libbinary-fs.so /lib/libbinary-fs.so
42
+
43
+ RUN openssl genrsa -3 -out /enclave-key.pem 3072
44
+
45
+ ENV SCONE_LOG=INFO
46
+ ENV SCONE_HEAP=256M
47
+ ENV SCONE_ALLOW_DLOPEN=1
48
+ ENV SCONE_EXTENSIONS_PATH=/lib/libbinary-fs.so
49
+
50
+ # Disabled production mode for testnet
51
+ # RUN scone-signer sign --key=/enclave-key.pem --env --production /usr/local/bin/python3
52
+
53
+ RUN rm -rf /enclave-key.pem
54
+
55
+ ENTRYPOINT ["/usr/local/bin/python", "/etny-trustedzone/trustedzone.py"]
56
+
@@ -0,0 +1,32 @@
1
+ #!/bin/bash -v
2
+
3
+ pip3 install pyinstaller
4
+ apk add binutils
5
+
6
+ cd /etny-trustedzone
7
+
8
+ cat trustedzone.py.tmpl | sed s/"__ENCLAVE_NAME_TRUSTEDZONE__"/"${ENCLAVE_NAME_TRUSTEDZONE}"/g > trustedzone.py
9
+
10
+ pyinstaller trustedzone.py
11
+
12
+ EXEC=(scone binaryfs / /binary-fs-dir -v \
13
+ --include '/usr/local/lib/python3.10/*' \
14
+ --include '/etny-trustedzone/*' \
15
+ --host-path=/etc/resolv.conf \
16
+ --host-path=/etc/hosts)
17
+
18
+
19
+ for FILE in `cat ./build/trustedzone/COLLECT-00.toc | grep '.so' | grep BINARY | awk -F "'" '{print $4}'`
20
+ do
21
+ EXEC+=(--include "${FILE}"'*')
22
+ done
23
+
24
+ rm -rf build dist trustedzone.spec
25
+
26
+ echo "${EXEC[@]}"
27
+
28
+ SCONE_MODE=auto
29
+ exec "${EXEC[@]}"
30
+
31
+
32
+ exit
@@ -0,0 +1,5 @@
1
+ ETNY_CHAIN_ID=8995
2
+ ETNY_SMART_CONTRACT_ADDRESS=0x549A6E06BB2084100148D50F51CF77a3436C3Ae7
3
+ ETNY_WEB3_PROVIDER=https://bloxberg.ethernity.cloud
4
+ ETNY_CLIENT_CHALLENGE=eyJjaXBoZXJ0ZXh0IjogImNjMDQ4Y2NjNzUxZDkwNjE2N2M3YTliNjZkZWZiYjVlMjE3N2E2NTU0MzYxNWEwNTYzYTBmMzViMzkiLCAibm9uY2UiOiAiMTZmYTk5MzRmNDcxMTczZTVmMjg5NDNlY2U4NjZiMzgiLCAiYXV0aFRhZyI6ICJmZTlmY2QyMDk5MzI1NTY2MTRlZTZmMTMwNzIwNzk0ZiIsICJ4IjogIjB4ZDU1ZjgwOWI5MGI0ZGQxYjk4YmJlYmYxYmQzNzlhYzEwNTU1MzFkMjYxMzBhYWU1MGI3MjA3ZGM0N2RlZjNkZWYzYTc1NTliYjkwMWQ1MmE1MWQ1YjNmNDNkODMyZmY5IiwgInkiOiAiMHgyYmMzYmE4ZjA2N2U3YjhiMGQ5NDM0ZWI4NjY2ZjA2ZGIxNjZhMjQ2M2YyNTE4NzcyYmVkYmUxMWM0ZTExNjIzZmIxODMzN2ZiNjRmNjE0OGY3YjEwZDgzMWE1NjYyZDgifQ==
5
+ ETNY_ORDER_ID=5602