Files: a01401f258acd7e0b1f4ecbe82cdd1bc26048b4c / index.js
1804 bytesRaw
1 | const Vertex = require('merkle-trie') |
2 | // The Kernel Exposes this Interface to VM instances it makes |
3 | const defaultInterface = require('./EVMinterface.js') |
4 | const VM = require('./vm.js') |
5 | const Environment = require('./environment.js') |
6 | |
7 | module.exports = class Kernel { |
8 | constructor (opts = {}) { |
9 | this.state = opts.state || new Vertex() |
10 | this.state.value = opts.code || this.state.value |
11 | this.interfaces = opts.interfaces || [defaultInterface] |
12 | this._vm = new VM(this.state.value) |
13 | } |
14 | |
15 | /** |
16 | * run the kernels code with a given enviroment |
17 | * The Kernel Stores all of its state in the Environment. The Interface is used |
18 | * to by the VM to retrive infromation from the Environment. |
19 | */ |
20 | async run (environment = new Environment({state: this}), interfaces = this.interfaces) { |
21 | /** |
22 | * Builds a import map with an array of given interfaces |
23 | */ |
24 | async function buildImports (kernelApi, imports, state) { |
25 | const result = {} |
26 | for (const Import of imports) { |
27 | const newIterface = new Import(kernelApi) |
28 | result[Import.name] = newIterface.exports |
29 | // initailize the import |
30 | await newIterface.initialize(state) |
31 | } |
32 | return result |
33 | } |
34 | |
35 | const initializedImports = await buildImports(this._vm, interfaces, this.state) |
36 | return await this._vm.run(environment, initializedImports) |
37 | } |
38 | |
39 | async messageReceiver (message) { |
40 | // let the code handle the message if there is code |
41 | const environment = new Environment({ |
42 | message: message |
43 | }) |
44 | let result = await this.run(environment) |
45 | if (!result.execption) { |
46 | this.state = result.state |
47 | } |
48 | } |
49 | |
50 | copy () { |
51 | return new Kernel({ |
52 | state: this.state.copy(), |
53 | code: this.code, |
54 | interfaces: this.interfaces, |
55 | parent: this.parent |
56 | }) |
57 | } |
58 | } |
59 |
Built with git-ssb-web