-
Notifications
You must be signed in to change notification settings - Fork 2
/
virtualMachine.js
420 lines (394 loc) · 19.1 KB
/
virtualMachine.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
/*********************
* virtualMachine.js *
*********************
*
* Exports the virtual machine class which handles managing various modules, their functions, state data and validation.
*
* This is not reliant on the Seed blockchain, but is instead fed info validated by the Seed blockchain. If its fed improper data, the functions will
* return improper values, giving differing hashes and therefore be rejected by other users. For this reason, this virtual machine was built before
* the blockchain portion is completed.
*
* Users can use the virtual machine to simulate functions being run, and selectively apply the changes to simualtions they choose.
*
* Exported Functions:
* getVirtualMachine()
* - Creates a new VirtualMachine object
*/
let virtualMachine = null;
module.exports = {
/**
* Creates a new VirtualMachine object
*/
getVirtualMachine : function() {
if (virtualMachine == null) {
virtualMachine = new VirtualMachine();
}
return virtualMachine;
},
/**
* Returns the mapping of unit tests for testing
*
* @return - The mapping of unit tests
*/
getUnitTests : function() {
return virtualMachineUnitTests;
}
}
const changeContextExporter = require("./changeContext.js");
const containerExporter = require("./container.js");
const conformHelper = require("../helpers/conformHelper.js");
const ledgerExporter = require("../ledger.js");
const entanglement = require("../entanglement.js");
const blockchain = require("../blockchain.js");
const transactionExporter = require("../transaction.js");
const messagingExporter = require("../messaging.js");
const moduleExporter = require("../module.js");
const unitTestingExporter = require("../tests/unitTesting.js");
class VirtualMachine {
constructor() {
this.modules = {};
this.ERROR = {
FailedToChangeState : "ERROR::FAILED TO CHANGE STATE"
}
}
/**
* Adds an externally created module to the virtual machine.
* The name of the module is used as the module lookup.
* Creates the module data in the ledger
*
* @param {Module} newModule - An externally created Module object
*/
addModule(newModule) {
this.modules[newModule.module] = newModule;
ledgerExporter.getLedger().addModuleData(newModule.module, newModule.initialData, newModule.initialUserData);
}
/**
* Adds a Seed user to be a part of the module's userbase in the ledger
*
* @param {object} moduleInfo - An options object that contains the module name as a variable
* @param {string} user - The public address of the user to add to the module
*/
addUser(moduleInfo, user) {
ledgerExporter.getLedger().addUserData(moduleInfo.module, user);
}
/**
* Gets A module stored in the virtual machine by module name.
* Uses module name as look-up in the key-value storage
*
* @param {object} info - An options object that contains the module name as a variable
* {string} info.module - The module name
*
* @return - The module found in the mapping
*/
getModule(info) {
return this.modules[info.module];
}
/**
* Gets a function stored in a module on the virtual machine.
*
* @param {object} info - An option object that has the module and function to get stored as variables
* {string} info.module - The module name
* {string} info.function - The functions name
*
* @return - The function found in the given module
*/
getFunction(info) {
return this.getModule(info).getFunctionByName(info.function);
}
/**
* Simulates a function being executed with the current state of the virtual machine.
* If the function is a state-modifying function, it returns a ChangeContext object regarding what
* changes occured to the ledger. If the function was a getter, it returns the data fetched by the getter.
*
* @param {object} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
* {string} info.function - The functions name
* {object} info.args - The arguments to pass into the function
* {string} info.user - The address of the user who is the sender of the function
* {array} info.txHashes - The hashes of the transaction hashes validated
*
* @return - ChangeContext if state-modifying function. Fetched data if getter function.
*/
simulate(info) {
let moduleToInvoke = this.getModule(info);
let moduleDataToInvoke = ledgerExporter.getLedger().getModuleData(info.module);
//If the user simulating this does not exist, add them to our ledger
if (!moduleToInvoke.doesUserExist(info.user)) {
this.addUser(info, info.user);
}
let moduleFunction = moduleToInvoke.getFunctionByName(info.function);
let moduleFunctionArgs = conformHelper.getFunctionArgs(moduleFunction.invoke);
let container = containerExporter.createContainer(moduleToInvoke.module, info.user, info.args, info.txHashes);
let result = undefined;
if (moduleFunctionArgs.length == 2) { //State-modifying function
let changeContext = changeContextExporter.createChangeContext(info.user);
try {
result = moduleFunction.invoke(container, changeContext); //Container is ledger, changeContext keeps track of changes
} catch (err) {
console.info("VirtualMachine::ERROR:: Failed to run state-modifying function", err);
}
} else if (moduleFunctionArgs.length == 1) { //Read-Only Getter
try {
result = moduleFunction.invoke(container); //Container is ledger
} catch (err) {
console.info("VirtualMachine::ERROR:: Failed to run read-only getter", err);
}
} else {
throw "VirtualMachine::ERROR::simulate: Invalid number of parameters for a module function";
}
return result;
}
/**
* Modifies the state of the virtual machine by the changes found in the chaneContext object
*
* @param {object} info - An options object that has the module
* {string} info.module - The name of the module being modified
* @param {ChangeContext} changeContext - A ChangeContext of changes to apply to the state of the virtual machine
*/
applyChangeContext(info, changeContext) {
ledgerExporter.getLedger().applyChanges(info.module, changeContext);
}
/**
* Simulates a function invocation in the virtual machine, and, if the state was modified, applies the changes to the virtual machine.
*
* @param {object} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
* {string} info.function - The functions name
* {object} info.args - The arguments to pass into the function
* {string} info.user - The address of the user who is the sender of the function
* {array} info.txHashes - The hashes of the transaction hashes validated
*
* @return - ChangeContext if state-modifying function. Fetched data if getter function.
*/
invoke(info, resultIfSimulate) {
let result = resultIfSimulate == undefined ? this.simulate(info) : JSON.parse(resultIfSimulate);
// TODO: change doesFullyConform to somehow compare it to a module.functionSchema[info.function] to constraint to data types, so functions can ask for certain types
if (result != undefined && conformHelper.doesFullyConform(result, { moduleData : "object", userData : "object" })) {
let users = Object.keys(result.userData);
let moduleDataKeys = Object.keys(result.moduleData);
if (users.length != 0 || moduleDataKeys.length != 0) {
this.applyChangeContext(info, result);
} else {
return this.ERROR.FailedToChangeState;
}
}
messagingExporter.invoke(info.module, info.function, "txHash", result);
return result;
}
/**
* Creates a transaction
*
* First it determines transactions that need to be validated, validates them, simulates our code execution, wraps it into a transaction,
* signs it, "receives" our new transaction for interpreting, and then return is.
*
* @param {*} account - The account used to create the transactiona nd sign it
* @param {*} mod - The name of the module who's code we are executing
* @param {*} func - The name of the function on the module who's code we are executing
* @param {*} args - The arguments passed into the function during execution
* @param {*} transactionsToValidate - The amount fo transactions we will validate as work
*
* @return - A newly created transaction, or null if transaction creation failed
*/
createTransaction(account, mod, func, args, transactionsToValidate) {
let tips = entanglement.getTipsToValidate(account.publicKey, transactionsToValidate);
let localSimulation = this.simulate({ module : mod, function : func, args : args, user : account.publicKey, txHashes : tips });
if (localSimulation.didChange()) {
let work = this.doWork(account, tips);
let transaction = transactionExporter.createNewTransaction(account.publicKey, { moduleName : mod, functionName : func, args : args, changeSet : JSON.stringify(localSimulation) }, work);
transaction.signature = account.sign(transaction.transactionHash);
this.incomingTransaction(transaction);
return transaction;
} else {
//console.info("FAILED", localSimulation);
return null;
}
}
/**
* Receives an incoming transaction and, if it is Proper and well formed, it tries to add it to the entanglement
*
* @param {*} transaction - The transaction to attempt to receive
*/
incomingTransaction(transaction) {
if (!entanglement.hasTransaction(transaction.transactionHash)) {
// If its a proper, formed transaction
if (transactionExporter.isTransactionProper(transaction)) {
// We add it to the entanglement
entanglement.tryAddTransaction(transaction);
return true;
} else {
console.info("SVM::incomingTx::Rejected ", transaction.transactionHash, "::malformed transaction");
}
} else {
console.info("SVM::incomingTx::Rejected ", transaction.transactionHash, "::duplicate transaction");
}
return false;
}
/**
* Takes an account and an array of tips to validate. It then validates them by doing work.
*
* @param {*} account - The account used to sign our work
* @param {*} tips - The transactions that we want to validate
*
* @return - An array of validation work
*/
doWork(account, tips) {
let result = [];
for(let i = 0; i < tips.length; i++) {
let transaction = tips[i];
let localSimulation = this.simulate({ module : transaction.execution.moduleName, function : transaction.execution.functionName, args : transaction.execution.args, user : transaction.sender, txHashes : transaction.getValidatedTXHashes() });
let localSimAsString = JSON.stringify(localSimulation);
if (localSimAsString == transaction.execution.changeSet) {
let moduleUsed = this.getModule({ module : transaction.execution.moduleName });
if (moduleUsed != undefined) {
let functionChecksum = moduleUsed.functionChecksums[transaction.execution.functionName];
let moduleChecksum = moduleUsed.moduleChecksum;
result.push( { transactionHash : transaction.transactionHash, moduleChecksum : moduleChecksum, functionChecksum : functionChecksum, changeSet : localSimAsString });
} else {
throw new Error("Failed to get module");
}
} else {
console.info("Simulated", localSimAsString, "Actual", transaction.execution.changeSet);
throw new Error("Failed to simulate tip");
}
}
return result;
}
/**
* Validation function wrapper confirming that a users claimed function that was executed was valid
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
* {string} info.function - The function name
* @param {*} invokeHash - The claimed hash to compare againsts
*/
isFunctionLeanInfoCorrect(info, invokeHash) {
let module = this.getModule(info);
if (module != undefined) {
return module.isFunctionLeanInfoCorrect(info, invokeHash);
} else {
return false;
}
}
/**
* Validation function wrapper confirming that a users claimed function that was executed was valid
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
* {string} info.function - The function name being validated
* {function} info.invoke - The function being validated
* @param {*} invokeHash - The claimed hash to compare againsts
*/
isFunctionCorrect(info, invokeHash) {
let module = this.getModule(info);
if (module != undefined) {
return module.isFunctionCorrect(info, invokeHash);
} else {
console.log("Failed to load module");
return false;
}
}
/**
* Wrapper function getting the lean hash of a module's name
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
*/
leanHashModule(info) {
let module = this.getModule(info);
return module.leanHash(info);
}
/**
* Wrapper function getting the full hash of an entire module, including the hashes of all functions
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
*/
fullHashModule() {
let module = this.getModule(info);
return module.fullHash(info);
}
/**
* Wrapper function getting the lean hash of a module's name
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
*/
leanHashFunction(info) {
let module = this.getModule(info);
return module.leanHashFunction(info);
}
/**
* Wrapper function getting the full hash of a function
*
* @param {*} info - An options object that has the module, function and arguments stored for function execution
* {string} info.module - The module name
* {string} info.function - The name of the function
*/
fullHashFunction(info) {
let module = this.getModule(info);
return module.fullHashFunction(info);
}
}
const virtualMachineUnitTests = {
/**
* Confirm the virtual machine can have modules added to it and be stored in the ledger.
*/
svm_modulesCanBeAdded : function(test, log) {
let svm = module.exports.getVirtualMachine();
svm.addModule(moduleExporter.getTestModule());
test.assert(svm.getModule({ module : "Test" }) != undefined, "Should have stored the created module");
},
/**
* Confirm the virtual machine can read a modules data from the ledger.
*/
svm_canReadModuleDataFromLedger : function(test, log) {
let ledgerData = ledgerExporter.getLedger().getModuleData("Test");
test.assert(ledgerData != undefined, "The Test module should exist in the ledger");
test.assertAreEqual(ledgerData.testValue, 5, "The Test.testValue data should have defaulted to 5");
},
/**
* Confirm “getter” functions can be invoked to fetch Module data.
*/
svm_canInvokeModuleGetterFunctions: function(test, log) {
let svm = module.exports.getVirtualMachine();
let testValue = svm.simulate({ module : "Test", function : "getTestValue", user : "ABC"});
test.assert(testValue, 5, "Value from getter should match default value of 5");
},
/**
* Confirm “setters” can be simulated
*/
svm_canSimulateModuleSetterFunctions : function(test, log) {
let svm = module.exports.getVirtualMachine();
let simulatedChangeSet = svm.simulate({ module : "Test", function : "addToTestValue", user : "ABC", args : { value : 2 }});
// Prove our simulation tries to add 2 to the test value
test.assert(simulatedChangeSet.moduleData.testValue, 2, "Should have simulated how much things would change if it added 2");
// Prove the simulation did not alter the real value
let testValue = svm.simulate({ module : "Test", function : "getTestValue", user : "ABC"});
test.assert(testValue, 5, "The testValue should still have been 5 as the simulation should not modify ledger");
},
/**
* Confirm “setters” can be invoked and the ledger updates accordingly.
*/
svm_canInvokeModuleSetterFunctionsWhichAndStateChanged : function(test, log) {
let svm = module.exports.getVirtualMachine();
let changes = svm.invoke({ module : "Test", function : "addToTestValue", user : "ABC", args : { value : 2 }});
// Prove our invoking got the same values as the simulation of trying to add 2
test.assert(changes.moduleData.testValue, 2, "Should have changed the test value by 2");
// Prove that invoking the test did change the ledgers value
let testValue = svm.simulate({ module : "Test", function : "getTestValue", user : "ABC"});
test.assert(testValue, 7, "The testValue should still have been 7 after adding 2 to the default value of 5");
},
/**
* Confirm transactions can be added to the virtual machine, executing them and storing their changes to the ledger.
*/
svm_addingTransactionsExecutesAndStoresInledger : function(test, log) {
entanglement.clearAll();
blockchain.clearAll();
let seedConstructorData = unitTestingExporter.getSeedConstructorTransaction();
let seedConstructorTx = transactionExporter.createExistingTransaction(seedConstructorData.sender, seedConstructorData.execution, seedConstructorData.validatedTransactions, seedConstructorData.transactionHash, seedConstructorData.signature, seedConstructorData.timestamp );
let svm = module.exports.getVirtualMachine();
svm.incomingTransaction(seedConstructorTx, false);
let txHash = seedConstructorTx.transactionHash;
test.assert(entanglement.getEntanglement().contains(txHash) != undefined, "Entanglement should have constructor stored");
}
}