-
Notifications
You must be signed in to change notification settings - Fork 25
/
SmartContracts.js
563 lines (496 loc) · 18.7 KB
/
SmartContracts.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
const SHA256 = require('crypto-js/sha256');
const enchex = require('crypto-js/enc-hex');
const { Base64 } = require('js-base64');
const { VM, VMScript } = require('vm2');
const BigNumber = require('bignumber.js');
const validator = require('validator');
const seedrandom = require('seedrandom');
const DB_PLUGIN_NAME = require('../plugins/Database.constants').PLUGIN_NAME;
const DB_PLUGIN_ACTIONS = require('../plugins/Database.constants').PLUGIN_ACTIONS;
const RESERVED_CONTRACT_NAMES = ['contract', 'blockProduction', 'null'];
const RESERVED_ACTIONS = ['createSSC'];
class SmartContracts {
// deploy the smart contract to the blockchain and initialize the database if needed
static async deploySmartContract(
ipc, transaction, blockNumber, timestamp, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
) {
try {
const { transactionId, refSteemBlockNumber, sender } = transaction;
const payload = JSON.parse(transaction.payload);
const { name, params, code } = payload;
if (name && typeof name === 'string'
&& code && typeof code === 'string') {
// the contract name has to be a string made of letters and numbers
if (!validator.isAlphanumeric(name)
|| RESERVED_CONTRACT_NAMES.includes(name)
|| name.length < 3
|| name.length > 50) {
return { logs: { errors: ['invalid contract name'] } };
}
const res = await ipc.send(
{ to: DB_PLUGIN_NAME, action: DB_PLUGIN_ACTIONS.FIND_CONTRACT, payload: { name } },
);
// for now the contracts are immutable
if (res.payload) {
// contract.code = code;
return { logs: { errors: ['contract already exists'] } };
}
// this code template is used to manage the code of the smart contract
// this way we keep control of what can be executed in a smart contract
let codeTemplate = `
RegExp.prototype.constructor = function () { };
RegExp.prototype.exec = function () { };
RegExp.prototype.test = function () { };
let actions = {};
###ACTIONS###
const execute = async function () {
try {
if (api.action && typeof api.action === 'string' && typeof actions[api.action] === 'function') {
if (api.action !== 'createSSC') {
actions.createSSC = null;
}
await actions[api.action](api.payload);
done(null);
}
} catch (error) {
done(error);
}
}
execute();
`;
// the code of the smart contarct comes as a Base64 encoded string
codeTemplate = codeTemplate.replace('###ACTIONS###', Base64.decode(code));
// compile the code for faster executions later on
const script = new VMScript(codeTemplate).compile();
const tables = {};
// prepare the db object that will be available in the VM
const db = {
// createTable is only available during the smart contract deployment
createTable: (tableName, indexes = []) => SmartContracts.createTable(
ipc, tables, name, tableName, indexes,
),
// perform a query find on a table of the smart contract
find: (table, query, limit = 1000, offset = 0, indexes = []) => SmartContracts.find(
ipc, name, table, query, limit, offset, indexes,
),
// perform a query find on a table of an other smart contract
findInTable: (contractName, table, query, limit = 1000, offset = 0, index = '', descending = false) => SmartContracts.find(
ipc, contractName, table, query, limit, offset, index, descending,
),
// perform a query findOne on a table of the smart contract
findOne: (table, query) => SmartContracts.findOne(ipc, name, table, query),
// perform a query findOne on a table of an other smart contract
findOneInTable: (contractName, table, query) => SmartContracts.findOne(
ipc, contractName, table, query,
),
// find the information of a contract
findContract: contractName => SmartContracts.findContract(ipc, contractName),
// insert a record in the table of the smart contract
insert: (table, record) => SmartContracts.dinsert(ipc, name, table, record),
};
// logs used to store events or errors
const logs = {
errors: [],
events: [],
};
const rng = seedrandom(`${prevRefSteemBlockId}${refSteemBlockId}${transactionId}`);
// initialize the state that will be available in the VM
const vmState = {
api: {
action: 'createSSC',
payload: params ? JSON.parse(JSON.stringify(params)) : null,
transactionId,
blockNumber,
refSteemBlockNumber,
steemBlockTimestamp: timestamp,
db,
BigNumber,
validator,
random: () => rng(),
debug: log => console.log(log), // eslint-disable-line no-console
// execute a smart contract from the current smart contract
executeSmartContract: async (
contractName, actionName, parameters,
) => SmartContracts.executeSmartContractFromSmartContract(
ipc, logs, sender, params, contractName, actionName,
JSON.stringify(parameters),
blockNumber, timestamp,
refSteemBlockNumber, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
),
// emit an event that will be stored in the logs
emit: (event, data) => typeof event === 'string' && logs.events.push({ contract: name, event, data }),
// add an error that will be stored in the logs
assert: (condition, error) => {
if (!condition && typeof error === 'string') {
logs.errors.push(error);
}
return condition;
},
},
};
const error = await SmartContracts.runContractCode(vmState, script, jsVMTimeout);
if (error) {
if (error.name && typeof error.name === 'string'
&& error.message && typeof error.message === 'string') {
return { errors: [`${error.name}: ${error.message}`] };
}
return { logs: { errors: ['unknown error'] } };
}
const newContract = {
name,
owner: sender,
code: codeTemplate,
codeHash: SHA256(codeTemplate).toString(enchex),
tables,
};
await ipc.send(
{ to: DB_PLUGIN_NAME, action: DB_PLUGIN_ACTIONS.ADD_CONTRACT, payload: newContract },
);
return { executedCodeHash: newContract.codeHash, logs };
}
return { logs: { errors: ['parameters name and code are mandatory and they must be strings'] } };
} catch (e) {
console.error('ERROR DURING CONTRACT DEPLOYMENT: ', e);
return { logs: { errors: [`${e.name}: ${e.message}`] } };
}
}
// execute the smart contract and perform actions on the database if needed
static async executeSmartContract(
ipc, transaction, blockNumber, timestamp, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
) {
try {
const {
transactionId,
sender,
contract,
action,
payload,
refSteemBlockNumber,
} = transaction;
if (RESERVED_ACTIONS.includes(action)) return { logs: { errors: ['you cannot trigger this action'] } };
const payloadObj = payload ? JSON.parse(payload) : {};
const res = await ipc.send(
{
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.FIND_CONTRACT,
payload: { name: contract },
},
);
const contractInDb = res.payload;
if (contractInDb === null) {
return { logs: { errors: ['contract doesn\'t exist'] } };
}
const contractCode = contractInDb.code;
const contractOwner = contractInDb.owner;
// prepare the db object that will be available in the VM
const db = {
// perform a query find on a table of the smart contract
find: (table, query, limit = 1000, offset = 0, indexes = []) => SmartContracts.find(
ipc, contract, table, query, limit, offset, indexes,
),
// perform a query find on a table of an other smart contract
findInTable: (contractName, table, query, limit = 1000, offset = 0, index = '', descending = false) => SmartContracts.find(
ipc, contractName, table, query, limit, offset, index, descending,
),
// perform a query findOne on a table of the smart contract
findOne: (table, query) => SmartContracts.findOne(ipc, contract, table, query),
// perform a query findOne on a table of an other smart contract
findOneInTable: (contractName, table, query) => SmartContracts.findOne(
ipc, contractName, table, query,
),
// find the information of a contract
findContract: contractName => SmartContracts.findContract(ipc, contractName),
// insert a record in the table of the smart contract
insert: (table, record) => SmartContracts.insert(ipc, contract, table, record),
// insert a record in the table of the smart contract
remove: (table, record) => SmartContracts.remove(ipc, contract, table, record),
// insert a record in the table of the smart contract
update: (table, record) => SmartContracts.update(ipc, contract, table, record),
};
// logs used to store events or errors
const results = {
executedCodeHash: contractInDb.codeHash,
logs: {
errors: [],
events: [],
},
};
const rng = seedrandom(`${prevRefSteemBlockId}${refSteemBlockId}${transactionId}`);
// initialize the state that will be available in the VM
const vmState = {
api: {
sender,
owner: contractOwner,
refSteemBlockNumber,
steemBlockTimestamp: timestamp,
transactionId,
blockNumber,
action,
payload: JSON.parse(JSON.stringify(payloadObj)),
db,
BigNumber,
validator,
random: () => rng(),
debug: log => console.log(log), // eslint-disable-line no-console
// execute a smart contract from the current smart contract
executeSmartContract: async (
contractName, actionName, parameters,
) => SmartContracts.executeSmartContractFromSmartContract(
ipc, results, sender, payloadObj, contractName, actionName,
JSON.stringify(parameters),
blockNumber, timestamp,
refSteemBlockNumber, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
),
// execute a smart contract from the current smart contract
// with the contractOwner authority level
executeSmartContractAsOwner: async (
contractName, actionName, parameters,
) => SmartContracts.executeSmartContractFromSmartContract(
ipc, results, contractOwner, payloadObj, contractName, actionName,
JSON.stringify(parameters),
blockNumber, timestamp,
refSteemBlockNumber, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
),
// execute a token transfer from the contract balance
transferTokens: async (
to, symbol, quantity, type,
) => SmartContracts.executeSmartContractFromSmartContract(
ipc, results, 'null', payloadObj, 'tokens', 'transferFromContract',
JSON.stringify({
from: contract,
to,
quantity,
symbol,
type,
}),
blockNumber, timestamp,
refSteemBlockNumber, refSteemBlockId, prevRefSteemBlockId, jsVMTimeout,
),
// emit an event that will be stored in the logs
emit: (event, data) => typeof event === 'string' && results.logs.events.push({ contract, event, data }),
// add an error that will be stored in the logs
assert: (condition, error) => {
if (!condition && typeof error === 'string') {
results.logs.errors.push(error);
}
return condition;
},
},
};
const error = await SmartContracts.runContractCode(vmState, contractCode, jsVMTimeout);
if (error) {
const { name, message } = error;
if (name && typeof name === 'string'
&& message && typeof message === 'string') {
return { logs: { errors: [`${name}: ${message}`] } };
}
return { logs: { errors: ['unknown error'] } };
}
return results;
} catch (e) {
// console.error('ERROR DURING CONTRACT EXECUTION: ', e);
return { logs: { errors: [`${e.name}: ${e.message}`] } };
}
}
// run the contractCode in a VM with the vmState as a state for the VM
static runContractCode(vmState, contractCode, jsVMTimeout) {
return new Promise((resolve) => {
try {
// console.log('vmState', vmState)
// run the code in the VM
const vm = new VM({
timeout: jsVMTimeout,
sandbox: {
...vmState,
done: (error) => {
// console.log('error', error);
resolve(error);
},
},
});
vm.run(contractCode);
} catch (err) {
resolve(err);
}
});
}
static async executeSmartContractFromSmartContract(
ipc, originalResults, sender, originalParameters,
contract, action, parameters,
blockNumber,
timestamp,
refSteemBlockNumber, refSteemBlockId, prevRefSteemBlockId,
jsVMTimeout,
) {
if (typeof contract !== 'string' || typeof action !== 'string' || (parameters && typeof parameters !== 'string')) return null;
const sanitizedParams = parameters ? JSON.parse(parameters) : null;
// check if a recipient or amountSTEEMSBD
// or isSignedWithActiveKey were passed initially
if (originalParameters && originalParameters.amountSTEEMSBD) {
sanitizedParams.amountSTEEMSBD = originalParameters.amountSTEEMSBD;
}
if (originalParameters && originalParameters.recipient) {
sanitizedParams.recipient = originalParameters.recipient;
}
if (originalParameters && originalParameters.isSignedWithActiveKey) {
sanitizedParams.isSignedWithActiveKey = originalParameters.isSignedWithActiveKey;
}
const results = {};
try {
const res = await SmartContracts.executeSmartContract(
ipc,
{
sender,
contract,
action,
payload: JSON.stringify(sanitizedParams),
refSteemBlockNumber,
},
blockNumber,
timestamp,
refSteemBlockId,
prevRefSteemBlockId,
jsVMTimeout,
);
if (res && res.logs && res.logs.errors !== undefined) {
res.logs.errors.forEach((error) => {
if (results.errors === undefined) {
results.errors = [];
}
if (originalResults.logs.errors === undefined) {
originalResults.logs.errors = []; // eslint-disable-line no-param-reassign
}
originalResults.logs.errors.push(error);
results.errors.push(error);
});
}
if (res && res.logs && res.logs.events !== undefined) {
res.logs.events.forEach((event) => {
if (results.events === undefined) {
results.events = [];
}
if (originalResults.logs.events === undefined) {
originalResults.logs.events = []; // eslint-disable-line no-param-reassign
}
originalResults.logs.events.push(event);
results.events.push(event);
});
}
if (res && res.executedCodeHash) {
results.executedCodeHash = res.executedCodeHash;
originalResults.executedCodeHash += res.executedCodeHash; // eslint-disable-line
}
} catch (error) {
results.errors = [];
results.errors.push(error);
}
return results;
}
static async createTable(ipc, tables, contractName, tableName, indexes = []) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.CREATE_TABLE,
payload: {
contractName,
tableName,
indexes,
},
});
if (res.payload === true) {
// add the table name to the list of table available for this contract
const finalTableName = `${contractName}_${tableName}`;
if (tables[finalTableName] === undefined) {
tables[finalTableName] = { // eslint-disable-line
size: 0,
hash: '',
nbIndexes: indexes.length,
};
}
}
}
static async find(ipc, contractName, table, query, limit = 1000, offset = 0, indexes = []) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.FIND,
payload: {
contract: contractName,
table,
query,
limit,
offset,
indexes,
},
});
return res.payload;
}
static async findOne(ipc, contractName, table, query) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.FIND_ONE,
payload: {
contract: contractName,
table,
query,
},
});
return res.payload;
}
static async findContract(ipc, contractName) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.FIND_CONTRACT,
payload: {
name: contractName,
},
});
return res.payload;
}
static async insert(ipc, contractName, table, record) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.INSERT,
payload: {
contract: contractName,
table,
record,
},
});
return res.payload;
}
static async dinsert(ipc, contractName, table, record) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.DINSERT,
payload: {
table: `${contractName}_${table}`,
record,
},
});
return res.payload;
}
static async remove(ipc, contractName, table, record) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.REMOVE,
payload: {
contract: contractName,
table,
record,
},
});
return res.payload;
}
static async update(ipc, contractName, table, record) {
const res = await ipc.send({
to: DB_PLUGIN_NAME,
action: DB_PLUGIN_ACTIONS.UPDATE,
payload: {
contract: contractName,
table,
record,
},
});
return res.payload;
}
}
module.exports.SmartContracts = SmartContracts;