-
Notifications
You must be signed in to change notification settings - Fork 7
/
service-logic.js
377 lines (345 loc) · 11.7 KB
/
service-logic.js
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
'use strict';
const express = require('express');
const Router = express.Router();
const { exec } = require('child_process');
const fs = require('fs');
const copy = require('recursive-copy');
const del = require('del');
const path = require('path');
const Helper = require('./helpers');
const { Api, JsonRpc, Serialize } = require('eosjs');
const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig');
const { TextEncoder, TextDecoder } = require('util');
const fetch = require('node-fetch');
const LOG_DEST = path.resolve("./docker-eosio-cdt/stdout.txt");
const ERR_DEST = path.resolve("./docker-eosio-cdt/stderr.txt");
const DEL_TARGETS = ["./docker-eosio-cdt/contracts/**", "!./docker-eosio-cdt/contracts"];
const DEST = path.resolve("./docker-eosio-cdt/contracts");
const CWD = path.resolve('./docker-eosio-cdt');
const OPTIONS = {
overwrite: true,
junk: false,
dot: false,
filter: [
'**/*.cpp',
'**/*.hpp',
'**/*.c',
'**/*.h',
'**/*.yml',
'**/*.yaml',
'**/*.md'
]
};
/**
* How to test:
* localhost:8081/api/eosio/deploy
* POST request
* 1. <source> - Absolute source file path
* 2. <endpoint> - Blockchain endpoint
* 3. <account_name> - account name on which the smart contract would be deployed
* 4. <private_key> - private key of account to sign the transaction
* 5. <abiSource> - Optional path to supply as replacement ABI in case we imported
*/
Router.post("/deploy", async (req, res) => {
const { body } = req;
try {
const deletedFiles = await del(DEL_TARGETS);
let results = null;
let resolvedPath = Helper.resolveHomePath(body["source"]);
let compileTarget = path.basename(resolvedPath);
let endpoint = path.basename(body["endpoint"]);
let account_name = path.basename(body["account_name"]);
let private_key = path.basename(body["private_key"]);
let permission = body["permission"];
let COMPILE_SCRIPT = "";
const directories = Helper.parseDirectoriesToInclude(path.dirname(resolvedPath));
results = await copy(path.dirname(resolvedPath), DEST, OPTIONS);
COMPILE_SCRIPT = "./setup_eosio_cdt_docker.sh "+compileTarget+" "+directories.join(' ');
console.log("Deleted files:\n", deletedFiles.join('\n'));
results.forEach((file) => console.log("Copied file: ", file["src"]));
console.log("Target entry file: ", compileTarget);
if(fs.lstatSync(resolvedPath).isDirectory())
throw new Error(`${resolvedPath} is a directory, not a valid entry file!`);
if(body["account_name"] === 'eosio')
throw new Error(
`Chosen account name is ${account_name}, which owns the system contract used
for authorizing new accounts. Aborting contract deployment...`
);
exec(COMPILE_SCRIPT, {
cwd: CWD
}, (err, stdout, stderr) => {
console.log('compile script ran');
let parsedStdOut = Helper.parseLog(Helper.getFile(LOG_DEST));
let parsedStdErr = Helper.parseLog(Helper.getFile(ERR_DEST));
if (err) {
let message = (err.message) ? err.message : message;
res.send({
compiled: false,
errors: [
message
],
stdout: parsedStdOut,
stderr: parsedStdErr
});
} else {
const COMPILED_CONTRACTS = path.resolve(
"./docker-eosio-cdt/compiled_contracts/" +
path.basename(compileTarget, '.cpp')
);
const { wasmPath, abiPath, abiContents = {}, programErrors } = Helper.fetchDeployableFilesFromDirectory(COMPILED_CONTRACTS);
if (programErrors.length > 0) {
res.send({
compiled: false,
errors: programErrors,
stdout: parsedStdOut,
stderr: parsedStdErr
})
} else {
console.log(`stdout: ${stdout}`);
let abi = (body["abiSource"] && body["abiSource"] != "null") ? body["abiSource"] : abiPath;
let _abiContents = (body["abiSource"] && body["abiSource"] != "null") ? fs.readFileSync(body["abiSource"], 'utf-8') : abiContents;
console.log(body["abiSource"], abiPath, abi, typeof body["abiSource"]);
deployContract(endpoint, account_name, private_key, permission, wasmPath, abi)
.then(result => {
console.log("Contract deployed successfully ", result);
res.send({
compiled: true,
wasmLocation: wasmPath,
abi: abi,
deployed: true,
abiContents: _abiContents,
errors: [],
output: result,
stdout: parsedStdOut,
stderr: parsedStdErr
});
})
.catch((err) => {
let message = (err.message) ? err.message : err;
console.log("Caught error: ", err, message);
res.send({
compiled: true,
wasmLocation: wasmPath,
abi: abi,
abiContents: _abiContents,
deployed: false,
errors: [
message
],
stdout: parsedStdOut,
stderr: parsedStdErr
});
});
}
}
});
} catch (ex) {
let err = ex;
if (typeof ex === 'object') {
err = ex.message;
}
res.send({
compiled: false,
stderr: err,
errors: [
ex.message
]
})
}
});
/**
* How to test:
* localhost:8081/api/eosio/compile
* POST request
* 1. <source> - Absolute source file path
*/
Router.post("/compile", async (req, res) => {
const { body } = req;
try {
const deletedFiles = await del(DEL_TARGETS);
let results = null;
let resolvedPath = Helper.resolveHomePath(body["source"]);
let compileTarget = path.basename(resolvedPath);
let COMPILE_SCRIPT = "";
const directories = Helper.parseDirectoriesToInclude(path.dirname(resolvedPath));
results = await copy(path.dirname(resolvedPath), DEST, OPTIONS);
COMPILE_SCRIPT = "./setup_eosio_cdt_docker.sh "+compileTarget+" "+directories.join(' ');
console.log("Deleted files:\n", deletedFiles.join('\n'));
results.forEach((file) => console.log("Copied file: ", file["src"]));
console.log("Target entry file: ", compileTarget);
if(fs.lstatSync(resolvedPath).isDirectory())
throw new Error(`${resolvedPath} is a directory, not a valid entry file!`);
exec(COMPILE_SCRIPT, {
cwd: CWD
}, (err, stdout, stderr) => {
if(!fs.existsSync(LOG_DEST)) {
fs.closeSync(fs.openSync(LOG_DEST, 'aw'))
}
let parsedStdOut = Helper.parseLog(Helper.getFile(LOG_DEST));
let parsedStdErr = Helper.parseLog(Helper.getFile(ERR_DEST));
if (err) {
res.send({
compiled: false,
errors: Helper.parseLog(err.message),
stdout: parsedStdOut,
stderr: parsedStdErr
});
} else {
const COMPILED_CONTRACTS = path.resolve(
"./docker-eosio-cdt/compiled_contracts/" +
path.basename(compileTarget, '.cpp')
);
const { wasmPath, abiPath, abiContents = {}, programErrors } = Helper.fetchDeployableFilesFromDirectory(COMPILED_CONTRACTS);
if (programErrors.length > 0) {
res.send({
compiled: false,
errors: programErrors,
stdout: parsedStdOut,
stderr: parsedStdErr
})
} else {
res.send({
compiled: true,
wasmLocation: wasmPath,
abi: abiPath,
abiContents: abiContents,
errors: programErrors,
stdout: parsedStdOut,
stderr: parsedStdErr
});
}
}
})
} catch (ex) {
let err = ex;
if (typeof ex === 'object') {
err = ex.message;
}
res.send({
compiled: false,
stderr: err,
errors: [
ex.message
]
})
}
});
/****
* How to test:
* localhost:8081/api/eosio/import
* The page should handle this for you.
* 1. <abiName>
* 2. <content>
*/
Router.post("/import", async (req, res) => {
const { body } = req;
const IMPORT_FOLDER = path.resolve("./docker-eosio-cdt/imported_abi/");
const DESTINATION = path.resolve("./docker-eosio-cdt/imported_abi/"+body["abiName"]);
try {
if (!fs.lstatSync(IMPORT_FOLDER).isDirectory())
fs.mkdirSync(IMPORT_FOLDER, {recursive:true});
else {
const clearImport = await del(["./docker-eosio-cdt/imported_abi/"+body["abiName"]]);
console.log("Cleared old import: ", clearImport);
}
fs.writeFile(DESTINATION, body["content"], (err) => {
if (err) {
console.log(err);
res.send({
imported: false,
errors: [
err.message
]
});
} else {
console.log("ABI imported to path: "+DESTINATION);
res.send({
imported: true,
abiPath: DESTINATION.toString(),
errors: []
});
}
})
} catch (ex) {
let err = ex;
if (typeof ex === 'object') {
err = ex.message;
}
res.send({
compiled: false,
stderr: err,
errors: [
ex.message
]
})
}
})
async function deployContract(blockchainUrl, account_name, private_key, permission, wasm_path, abi_path){
if(blockchainUrl.indexOf("http://") < 0)
{
blockchainUrl = "http://" + blockchainUrl;
}
const rpc = new JsonRpc(blockchainUrl, { fetch });
const signatureProvider = new JsSignatureProvider([private_key]);
const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() });
const buffer = new Serialize.SerialBuffer({
textEncoder: api.textEncoder,
textDecoder: api.textDecoder,
});
const wasm = fs.readFileSync(wasm_path).toString('hex');
let abi = JSON.parse(fs.readFileSync(abi_path, 'utf8'));
const abiDefinition = api.abiTypes.get('abi_def');
// need to make sure abi has every field in abiDefinition.fields
// otherwise serialize throws error
abi = abiDefinition.fields.reduce(
(acc, { name: fieldName }) => Object.assign(acc, { [fieldName]: acc[fieldName] || [] }),
abi,
);
abiDefinition.serialize(buffer, abi);
try{
return await api.transact(
{
actions: [
{
account: 'eosio',
name: 'setcode',
authorization: [
{
actor: account_name,
permission: permission,
},
],
data: {
account: account_name,
vmtype: 0,
vmversion: 0,
code: wasm,
},
},
{
account: 'eosio',
name: 'setabi',
authorization: [
{
actor: account_name,
permission: permission,
},
],
data: {
account: account_name,
abi: Buffer.from(buffer.asUint8Array()).toString('hex'),
},
},
],
},
{
blocksBehind: 3,
expireSeconds: 30,
}
);
}
catch(err){
throw("Error while deploying contract - " + err)
}
}
module.exports = Router;