@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,613 @@
1
+ require('dotenv').config();
2
+ require('dotenv').config({path: './app/.env'});
3
+ require('dotenv').config({path: '/app/.env'});
4
+
5
+
6
+
7
+
8
+ const ethers = require('ethers');
9
+ const fs = require("fs");
10
+ const etny_crypto = require("./etny_crypto");
11
+ const {DOReqMetadata, Order} = require("./models");
12
+ const {getWalletAddress} = require("./wallet");
13
+ const {TaskStatus} = require("./task_status");
14
+ const SwiftStreamService = require("./swift_stream_service");
15
+
16
+ const contract_abi = require('./pox_abi');
17
+ const validator_contract_abi = require('./validator_abi');
18
+ const image_registry_abi = require('./image_registry_abi');
19
+ const {sha256} = require("./etny_crypto");
20
+ const { ObjectCreatedCompleteMultipartUpload } = require('minio');
21
+
22
+
23
+
24
+ class EtnyTrustedZone {
25
+
26
+ static debug = false;
27
+
28
+ constructor(swiftStreamClient) {
29
+ console.log('Initializing...');
30
+ this.version = 'v3';
31
+ this.swiftStreamService = swiftStreamClient;
32
+ this.etny_bucket = "validator";
33
+ this.setInitializers();
34
+ }
35
+
36
+ setInitializers() {
37
+ this.is_valid_client_data = true;
38
+ this.private_key_file = "/private/key.pem";
39
+ this.cert_file = "/app/cert.pem";
40
+ this.pub_cert_file = "/app/app.pem";
41
+ this.payload = "payload.etny";
42
+ this.input = "input.txt";
43
+ this.result_file = "/app/result.txt";
44
+ this.transaction_file = "/app/transaction.txt";
45
+ this.smart_contract_address = "0x549A6E06BB2084100148D50F51CF77a3436C3Ae7";
46
+ this.validator_contract_address = "0xAE7488b3aACb8415bE66d78C05D279BA5A86820E";
47
+ this.image_registry_address = "0x15D73a742529C3fb11f3FA32EF7f0CC3870ACA31";
48
+
49
+ this.chain_id = 8995;
50
+ this.web3_provider = "https://bloxberg.ethernity.cloud";
51
+ this.signed_tx_as_bytes = null;
52
+ this.client_challenge = "";
53
+ this.processed_orders = {};
54
+
55
+ if (this.etny_mode === "TEST") {
56
+ this.private_key_file = "/private/key.pem";
57
+ this.cert_file = "/app/cert.pem";
58
+ this.payload = "./app/payload.js";
59
+ this.input = "./app/input.txt";
60
+ this.result_file = "./app/result.txt";
61
+ this.transaction_file = "./app/transaction.txt";
62
+ this.pub_cert_file = "./app/enclave_pub_cert.pem";
63
+ }
64
+
65
+ if (this.etny_mode === "LOCAL_TEST") {
66
+ this.private_key_file = "./certs/key.pem";
67
+ this.cert_file = "./certs/cert.pem";
68
+ this.payload = "./app/payload.js";
69
+ this.input = "./app/input.txt";
70
+ this.result_file = "./app/result.txt";
71
+ this.transaction_file = "./app/transaction.txt";
72
+ this.pub_cert_file = "./app/enclave_pub_cert.pem";
73
+ }
74
+ }
75
+
76
+ async create() {
77
+
78
+ console.log('Init Web3');
79
+ this.initWeb3();
80
+
81
+ this.walletValidatorPrivateKey = await this.swiftStreamService.getFileContent(this.etny_bucket, "privateKey");
82
+ //console.log(this.walletValidatorPrivateKey.trim());
83
+ this.walletValidator = new ethers.Wallet(this.walletValidatorPrivateKey.trim(), this.w3);
84
+ //console.log(this.walletValidator.address, this.walletValidator.privateKey);
85
+ this.etny_validator = new ethers.Contract(this.validator_contract_address, validator_contract_abi, this.w3);
86
+ this.etny_validator_signer = new ethers.Contract(this.validator_contract_address, validator_contract_abi, this.walletValidator);
87
+
88
+
89
+ return true;
90
+ }
91
+
92
+ loadEnv() {
93
+ if (process.env.ETNY_CHAIN_ID) {
94
+ this.chain_id = parseInt(process.env.ETNY_CHAIN_ID);
95
+ }
96
+
97
+ if (process.env.ETNY_SMART_CONTRACT_ADDRESS) {
98
+ this.smart_contract_address = process.env.ETNY_SMART_CONTRACT_ADDRESS.trim();
99
+ }
100
+
101
+ if (process.env.ETNY_WEB3_PROVIDER) {
102
+ this.web3_provider = process.env.ETNY_WEB3_PROVIDER.trim();
103
+ }
104
+
105
+ if (process.env.ETNY_CLIENT_CHALLENGE) {
106
+ this.client_challenge = process.env.ETNY_CLIENT_CHALLENGE.trim();
107
+ }
108
+ if (process.env.ETNY_ORDER_ID) {
109
+ this.order_id = parseInt(process.env.ETNY_ORDER_ID);
110
+ }
111
+ }
112
+
113
+ printEnv() {
114
+ console.log('CHAIN ID:', this.chain_id);
115
+ console.log('SMART CONTRACT ADDRESS:', this.smart_contract_address);
116
+ console.log('WEB3 PROVIDER:', this.web3_provider);
117
+ console.log('ENCRYPTED CHALLENGE:', this.client_challenge);
118
+ console.log('ORDER ID:', this.order_id);
119
+ }
120
+
121
+ initWeb3() {
122
+ // Create an ethers.js provider connected to the Bloxberg network
123
+ this.w3 = new ethers.providers.JsonRpcProvider(this.web3_provider);
124
+ //this.walletSigner = new ethers.Wallet(this.walletPrivateKey, this.w3);
125
+ // Create an instance of the contract using the ABI and address
126
+ this.etny = new ethers.Contract(this.smart_contract_address, contract_abi, this.w3);
127
+ this.etny_signer = new ethers.Contract(this.smart_contract_address, contract_abi, this.walletSigner);
128
+ this.image_registry = new ethers.Contract(this.image_registry_address, image_registry_abi, this.w3);
129
+ // this.image_registry_signer = new ethers.Contract(this.image_registry_address, image_registry_abi, this.walletSigner);
130
+ }
131
+
132
+ async readEnv() {
133
+ try {
134
+ console.log('Getting .env if exists...');
135
+ //#const envFile = await this.swiftStreamService.getFileContent(this.etny_bucket, ".env");
136
+ //console.log("Env:", envFile);
137
+ //console.log("Saving .env file...");
138
+ //await fs.promises.writeFile('.env', envFile);
139
+ //require('dotenv').config();
140
+
141
+ this.version = 'v3';
142
+ this.etny_mode = "PRODUCTION";
143
+ console.log(`ETNY Validator [${this.version}] - running in ${this.etny_mode} MODE`);
144
+ console.log(process.env);
145
+
146
+ return true;
147
+ } catch (e) {
148
+ return false;
149
+ }
150
+ }
151
+
152
+ // convert client challenge
153
+ readClientChallenge() {
154
+ this.encrypted_tuple = etny_crypto.encryptedDataFromBase64Json(this.client_challenge);
155
+ }
156
+
157
+ generateNodeChallenge(length = 20) {
158
+ const lowercaseOnly = [...Array(length)].map(() => Math.random().toString(36)[2]).join('');
159
+ console.log('random challenge:', lowercaseOnly);
160
+ this.enclave_challenge = lowercaseOnly;
161
+ return this.enclave_challenge;
162
+ }
163
+
164
+ decodeClientDataAndGenerateWallet() {
165
+ console.log('started decoding challenge...');
166
+ const decryptedResult = etny_crypto.decrypt(this.private_key_file, this.encrypted_tuple);
167
+ if (!decryptedResult) {
168
+ return false;
169
+ } else {
170
+ console.log('decrypted_string = ', decryptedResult);
171
+ const [publicKey, privateKey] = getWalletAddress(decryptedResult, this.enclave_challenge);
172
+ this.wallet = publicKey;
173
+ this.walletPrivateKey = privateKey;
174
+
175
+ console.log("wallet = ", this.wallet);
176
+ console.log("private = ", this.walletPrivateKey);
177
+
178
+ return true;
179
+ }
180
+ }
181
+
182
+ extractSigner(message, signature) {
183
+ return ethers.utils.verifyMessage(message, signature);
184
+ }
185
+
186
+ async validateClientPayload(payload_data, input_data) {
187
+ if (this._metadata.payload_metadata_obj.checksum !== null) {
188
+ const payload_checksum = sha256(payload_data);
189
+ console.log('payload checksum: ', payload_checksum, "===", this._metadata.payload_metadata_obj.checksum);
190
+ // check the wallet address that signed payload checksum is the one from order metadata
191
+ const payload_signer = this.extractSigner(payload_checksum, this._metadata.payload_metadata_obj.checksum);
192
+ console.log("payload_signer", payload_signer);
193
+ console.log("this._order_metadata.do_owner.toLowerCase()", this._order_metadata.do_owner.toLowerCase());
194
+ if (payload_signer.toLowerCase() !== this._order_metadata.do_owner.toLowerCase()) {
195
+ this.task_code = TaskStatus.PAYLOAD_CHECKSUM_ERROR;
196
+ this.task_result = 'PAYLOAD CHECKSUM DOESN\'T MATCH';
197
+ this.is_valid_client_data = false;
198
+ return;
199
+ }
200
+ }
201
+ if (this._metadata.input_metadata_obj.checksum !== null) {
202
+ const input_checksum = sha256(input_data);
203
+ console.log('input checksum: ', input_checksum, '===', this._metadata.input_metadata_obj.checksum);
204
+ // check the wallet address that signed input checksum is the one from order metadata
205
+ const input_signer = this.extractSigner(input_checksum, this._metadata.input_metadata_obj.checksum);
206
+ console.log("input_signer", input_signer);
207
+ console.log("this._order_metadata.do_owner.toLowerCase()", this._order_metadata.do_owner.toLowerCase());
208
+ if (input_signer.toLowerCase() !== this._order_metadata.do_owner.toLowerCase()) {
209
+ this.task_code = TaskStatus.INPUT_CHECKSUM_ERROR;
210
+ this.task_result = 'INPUT CHECKSUM DOESN\'T MATCH';
211
+ this.is_valid_client_data = false;
212
+ }
213
+ }
214
+ }
215
+
216
+ wait(timeout) {
217
+ return new Promise(resolve => {
218
+ setTimeout(resolve, timeout);
219
+ });
220
+ }
221
+
222
+ async waitForObjectInBucket(bucketName, objectName, timeout = 600) {
223
+ let i = 0;
224
+ console.log(`Checking if object ${objectName} exists in bucket ${bucketName}`);
225
+ while (true) {
226
+ await this.wait(1000);
227
+ i++;
228
+ if (i % 20 === 0)
229
+ console.log(`Checking if object ${objectName} exists in bucket ${bucketName}`);
230
+ if (i > timeout) {
231
+ break;
232
+ }
233
+ const [status, result] = await this.swiftStreamService.isObjectInBucket(bucketName, objectName);
234
+ if (result) {
235
+ break;
236
+ }
237
+ }
238
+
239
+ console.log('secure lock finished the execution');
240
+ }
241
+
242
+ async waitForTask() {
243
+ console.log('Waiting for payload and input');
244
+ await this.waitForObjectInBucket(this.etny_bucket, "result.txt.securelock");
245
+ this.task_result = await this.getFileContentAndDecrypt(this.etny_bucket, "result.txt.securelock");
246
+ this.task_code = await this.getFileContentAndDecrypt(this.etny_bucket, "result_code.txt.securelock");
247
+ }
248
+
249
+ async getFileContentAndDecrypt(bucketName, objectName, isEmptyInput = false) {
250
+ try {
251
+ const encryptedBase64 = await this.swiftStreamService.getFileContent(bucketName, objectName);
252
+ console.log(`File ${objectName} downloaded from swift stream successfully`);
253
+ console.log(encryptedBase64);
254
+ if (isEmptyInput) {
255
+ return encryptedBase64;
256
+ }
257
+
258
+ console.log('Decrypting the file with private key:');
259
+ const encryptedTuple = etny_crypto.encryptedDataFromBase64Json(encryptedBase64);
260
+ console.log('encryptedTuple: ', encryptedTuple);
261
+ const decryptedResult = etny_crypto.decrypt(this.private_key_file, encryptedTuple);
262
+ console.log('decryptedResult: ', decryptedResult);
263
+ return decryptedResult;
264
+ } catch (e) {
265
+ console.log('Error:', e);
266
+ console.log(`Failed to get ${objectName} file`);
267
+ return false;
268
+ }
269
+ }
270
+
271
+ async getSecureLockPublicKey() {
272
+ console.log('Getting the public key of the secure lock enclave');
273
+ let imageHash = this._metadata.image_hash;
274
+ console.log('Image Hash Secure lock:', imageHash);
275
+ if (EtnyTrustedZone.debug) {
276
+ imageHash = 'v3-hash-1';
277
+ }
278
+ this.secureLockPublicKey = await this.image_registry.getImageCertPublicKey(imageHash);
279
+ console.log('public key of the SecureLock enclave:', this.secureLockPublicKey)
280
+ }
281
+
282
+ async encryptFileAndPushToSwiftStream(fileData, fileName) {
283
+ try {
284
+ const encryptedInput = etny_crypto.encrypt(this.secureLockPublicKey, fileData);
285
+ const encryptedInputBase64 = etny_crypto.encryptedDataToBase64Json(encryptedInput);
286
+
287
+ // File name should end with the '.securelock' extension
288
+ fileName += '.securelock';
289
+ // const data = Buffer.from(encryptedInputBase64, 'utf8');
290
+ const status = this.swiftStreamService.putFileContent(this.etny_bucket, fileName, '', encryptedInputBase64);
291
+ if (status) {
292
+ console.log(`File ${fileName} encrypted and saved to swift stream successfully`);
293
+ }
294
+ } catch (e) {
295
+ console.log('encryptFileAndPushToSwiftStream:', e);
296
+ }
297
+ }
298
+
299
+ checkIfIsEmptyInput() {
300
+ const empty_input_checksum = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
301
+ const input_signer = this.extractSigner(empty_input_checksum, this._metadata.input_metadata_obj.checksum);
302
+ return input_signer.toLowerCase() === this._order_metadata.do_owner.toLowerCase();
303
+ }
304
+
305
+ async prepareContextForSecureLock() {
306
+ await this.getSecureLockPublicKey();
307
+ const payloadData = await this.getFileContentAndDecrypt(this.etny_bucket, 'payload.etny');
308
+ console.log('payloadData:', payloadData);
309
+ console.log('payloadDataChecksum:', sha256(payloadData));
310
+ const isEmptyInput = this.checkIfIsEmptyInput();
311
+ const inputData = await this.getFileContentAndDecrypt(this.etny_bucket, 'input.txt', isEmptyInput);
312
+
313
+ console.log('Validate client payload and input');
314
+ await this.validateClientPayload(payloadData, inputData);
315
+ if (this.is_valid_client_data) {
316
+ console.log('Client payload and input are valid');
317
+ } else {
318
+ console.log('Client payload and input are NOT valid');
319
+ return false;
320
+ }
321
+
322
+ console.log('Pushing payload.etny.securelock');
323
+ await this.encryptFileAndPushToSwiftStream(payloadData, this.payload);
324
+ console.log('Pushing input.txt.securelock');
325
+ await this.encryptFileAndPushToSwiftStream(inputData, this.input);
326
+
327
+ return true;
328
+ }
329
+
330
+ async getDORequestMetadata() {
331
+ const o_result = await this.etny.functions._getOrder(this.order_id);
332
+ const order = new Order(o_result, this.order_id);
333
+ // console.log('order', order);
334
+ this._order_metadata = order;
335
+ const o_metadata = await this.etny.functions._getDORequestMetadata(order.do_req);
336
+ // console.log('o_metadata', o_metadata);
337
+ this._metadata = new DOReqMetadata(o_metadata, order.do_req);
338
+ // console.log('metadata', this._metadata);
339
+ }
340
+
341
+ resetPrivateCertFile() {
342
+ console.log('Resetting the cert file');
343
+ try {
344
+ // const fd = fs.openSync(this.private_key_file, 'w+');
345
+ fs.truncate(this.private_key_file, 0, function () {
346
+ console.log('Private certificate file was cleaned.')
347
+ });
348
+ // fs.closeSync(fd);
349
+ } catch (e) {
350
+ console.log('Error while removing the private key file content', e);
351
+ }
352
+ const content = fs.readFileSync(this.private_key_file, 'utf8');
353
+ console.log('cert file content', content, '##################');
354
+ }
355
+
356
+ async savePublicCert() {
357
+ try {
358
+ const content = await fs.promises.readFile(this.cert_file, 'utf8');
359
+ await fs.promises.writeFile(this.pub_cert_file, content);
360
+ console.log(`Public certificate saved to ${this.pub_cert_file}`);
361
+ console.log(`PUBLIC_KEY:`);
362
+ console.log(content);
363
+
364
+ await this.swiftStreamService.putFileContent(this.etny_bucket, 'cert.pem', this.pub_cert_file);
365
+ } catch (err) {
366
+ console.error(err);
367
+ }
368
+ }
369
+
370
+ buildResult() {
371
+ this.result = `${this.version}:${this.task_code}:${this.task_result_checksum}:${this.enclave_challenge}:`;
372
+ }
373
+
374
+ getResultChecksum() {
375
+ this.task_result_checksum = etny_crypto.sha256(this.task_result);
376
+ }
377
+
378
+ async buildTransaction() {
379
+ this.buildResult();
380
+
381
+ console.log(`adding result to order ${this.order_id}`);
382
+
383
+ // Call a method in the contract and get the encoded data
384
+ const args = [this.order_id, this.result];
385
+ const nonce = await this.walletSigner.getTransactionCount();
386
+ const tx = await this.etny_signer.populateTransaction._addResultToOrder(...args);
387
+
388
+ // Create a transaction object
389
+ const transaction = {
390
+ ...tx,
391
+ nonce,
392
+ gasLimit: ethers.utils.hexlify(1000000),
393
+ gasPrice: ethers.utils.parseUnits('1', 'mwei')
394
+ };
395
+
396
+ // Sign the transaction and send it to the network
397
+ const signedTransaction = await this.walletSigner.signTransaction(transaction);
398
+ this.signed_tx_as_bytes = signedTransaction;
399
+ console.log(signedTransaction);
400
+ return signedTransaction;
401
+ }
402
+
403
+ async saveTransaction() {
404
+ try {
405
+ const tx = await this.swiftStreamService.putFileContent(this.etny_bucket, 'transaction.txt', this.transaction_file, this.signed_tx_as_bytes);
406
+ console.log(tx);
407
+ const result = await this.swiftStreamService.getFileContent(this.etny_bucket, 'transaction.txt');
408
+ console.log('Getting file transaction.txt :', result);
409
+ } catch (e) {
410
+ console.log('Save transaction error: ', e);
411
+ }
412
+
413
+ }
414
+
415
+ async saveResult() {
416
+ try {
417
+ console.log('Encrypting result with public key:', this._metadata.public_key);
418
+ const encrypted = etny_crypto.encryptWithPublicKey(this._metadata.public_key, this.task_result);
419
+ console.log('Encrypted result:', encrypted.toString('hex'));
420
+ const result = await this.swiftStreamService.putFileContent(this.etny_bucket, 'result.txt', this.result_file, encrypted.toString('hex'));
421
+ console.log('Save result put: ', result);
422
+
423
+ const result1 = await this.swiftStreamService.getFileContent(this.etny_bucket, 'result.txt');
424
+ console.log('Getting file transaction.txt :', result1);
425
+ } catch (e) {
426
+ console.log('Save result error: ', e);
427
+ }
428
+ }
429
+
430
+ async execute() {
431
+
432
+ const o_count = await this.etny.functions._getOrdersCount();
433
+
434
+ for (let order_id = o_count - 1; order_id >= 0; order_id--) {
435
+
436
+ this.order_id = order_id;
437
+ if (this.processed_orders[order_id] == true)
438
+ continue
439
+
440
+ try {
441
+
442
+ await this.getDORequestMetadata();
443
+ if (this._order_metadata.status != 2) {
444
+ console.log(`Skipping order ${this.order_id} because is not closed`);
445
+ continue;
446
+ }
447
+
448
+ let validation_result = await this.etny_validator.functions.isValidationReady(this.order_id);
449
+ if (validation_result[0] == true) {
450
+ console.log(`Skipping order ${this.order_id} because is validated already`);
451
+ this.processed_orders[order_id] = true;
452
+ continue;
453
+ }
454
+
455
+ console.log(`Validating order ${this.order_id}`);
456
+
457
+ let challenge_ipfs_hash = this._metadata._metadata1.split(':')[4];
458
+ let image_ipfs_hash = this._metadata._metadata1.split(':')[1];
459
+
460
+
461
+ let session = await this.image_registry.functions.getTrustedZoneImageSession(image_ipfs_hash);
462
+
463
+ //console.log('session', session[0]);
464
+
465
+ this.private_key_file = "/private/" + session + "/key.pem";
466
+ this.cert_file = "/app/" + session + "/cert.pem";
467
+ this.pub_cert_file = "/app/" + session + "/app.pem";
468
+
469
+ if (fs.existsSync(this.private_key_file)) {
470
+ console.log("Validating using session", session[0]);
471
+ }
472
+ else {
473
+ //console.log("Wrong session", session[0]);
474
+ this.processed_orders[order_id] = true;
475
+ continue;
476
+ }
477
+
478
+ //console.log(this.private_key_file, this.cert_file, this.pub_cert_file);
479
+
480
+ this.client_challenge = await this.swiftStreamService.getFileContent(this.etny_bucket, challenge_ipfs_hash);
481
+
482
+ //console.log('challenge_content', this.client_challenge);
483
+
484
+ const o_result = await this.etny.functions._getResultFromOrder(this.order_id);
485
+ let tx = o_result[0].split(':')[1];
486
+
487
+ //console.log('tx', tx);
488
+
489
+ tx = tx.startsWith('0x') ? tx : `0x${tx}`;
490
+
491
+ //console.log('tx', tx);
492
+
493
+ const parsedTransaction = ethers.utils.parseTransaction(tx);
494
+ //console.log("pt", parsedTransaction);
495
+ const iface = new ethers.utils.Interface(contract_abi);
496
+ const decodedData = iface.parseTransaction({ data: parsedTransaction.data, value: parsedTransaction.value });
497
+ //console.log("dd", decodedData);
498
+
499
+ this.enclave_challenge = decodedData.args._result.split(':')[3];
500
+
501
+ //console.log("enclave_challenge", this.enclave_challenge);
502
+
503
+ //console.log('started decoding challenge...');
504
+
505
+ this.readClientChallenge();
506
+
507
+
508
+ const decryptedResult = etny_crypto.decrypt(this.private_key_file, this.encrypted_tuple);
509
+ if (!decryptedResult) {
510
+ this.processed_orders[order_id] = true;
511
+ continue;
512
+ } else {
513
+ //console.log('decrypted_string = ', decryptedResult);
514
+ const [publicKey, privateKey] = getWalletAddress(decryptedResult, this.enclave_challenge);
515
+ this.wallet = publicKey;
516
+ this.walletPrivateKey = privateKey;
517
+ }
518
+ //console.log("wallet = ", this.wallet);
519
+ //console.log("private = ", this.walletPrivateKey);
520
+
521
+ if (this.wallet == parsedTransaction.from) {
522
+ this.processed_orders[order_id] = true;
523
+ await this.etny_validator_signer.validateOrder(this.order_id, true);
524
+ console.log("Validated!")
525
+ }
526
+ else {
527
+ this.processed_orders[order_id] = true;
528
+ await this.etny_validator_signer.validateOrder(this.order_id, false);
529
+ console.log("Invalidated!")
530
+ }
531
+
532
+ }
533
+ catch (e) {
534
+ if (e.data) {
535
+ console.log('Transaction failed: ', e.data)
536
+ } else {
537
+ console.log('Error in getting validationResult:', e);
538
+ }
539
+ this.processed_orders[order_id] = true;
540
+ continue
541
+ }
542
+ }
543
+
544
+ return true;
545
+ }
546
+ }
547
+
548
+ function initSwiftStreamClient() {
549
+ console.log('Initializing SwiftStream Service...');
550
+ const swiftStreamClient = new SwiftStreamService(
551
+ EtnyTrustedZone.debug ? "localhost" : "etny-swift-stream",
552
+ 9000,
553
+ "swiftstreamadmin",
554
+ "swiftstreamadmin");
555
+ console.log('SwiftStream Service started.');
556
+ console.log('################################');
557
+
558
+ return swiftStreamClient;
559
+ }
560
+
561
+ async function execute() {
562
+ console.log('########################################');
563
+ console.log('########################################');
564
+ console.log('########## [ETNY Validator] ##########');
565
+ console.log('########################################');
566
+ console.log('########################################');
567
+ console.log('');
568
+ console.log('');
569
+ console.log('');
570
+
571
+ const swiftStreamClient = initSwiftStreamClient();
572
+
573
+ const app = new EtnyTrustedZone(swiftStreamClient);
574
+
575
+ const hasReadEnvFile = await app.readEnv();
576
+ if (!hasReadEnvFile && !EtnyTrustedZone.debug) {
577
+ console.log(`Failed reading .env file.`);
578
+ await app.savePublicCert();
579
+ return;
580
+ }
581
+
582
+ if (process.env.ETNY_MODE === "PUBLIC_KEY") {
583
+ await app.savePublicCert();
584
+ } else {
585
+ while(true) {
586
+ console.log('Creating the application...');
587
+
588
+
589
+ const created = await app.create();
590
+
591
+ if (!created) {
592
+ console.log(`Failed at creation step, not able decoding input metadata, exiting.`);
593
+ return;
594
+ }
595
+
596
+ const wasExecuted = await app.execute();
597
+ if (!wasExecuted) {
598
+ console.log('Task execution failed!');
599
+ return;
600
+ }
601
+
602
+ console.log('Finished process.');
603
+ }
604
+ }
605
+ }
606
+
607
+ (async () => {
608
+ try {
609
+ await execute();
610
+ } catch (e) {
611
+ console.log(e);
612
+ }
613
+ })();