git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: d6ecef73fd6edc80197140774535f1adea617314

Files: d6ecef73fd6edc80197140774535f1adea617314 / index.js

1683 bytesRaw
1const Graph = require('ipld-graph-builder')
2const Kernel = require('./kernel.js')
3const crypto = require('./crypto')
4
5module.exports = class Hypervisor {
6 constructor (opts) {
7 this._opts = {
8 hypervisor: this,
9 VMs: {}
10 }
11
12 this.graph = new Graph(opts.dag)
13 this._vmInstances = new Map()
14 Object.assign(this._opts, opts)
15 }
16
17 async getInstance (port) {
18 const id = await this.generateID(port.id)
19 let kernel = this._vmInstances.get(id)
20 if (!kernel) {
21 // load the container from the state
22 await this.graph.tree(port, 2)
23
24 // create a new kernel instance
25 const opts = Object.assign({
26 state: port.vm,
27 id: port.id
28 }, this._opts)
29
30 kernel = new Kernel(opts)
31 await kernel.start()
32 kernel.on('idle', () => {
33 this._vmInstances.delete(id)
34 })
35 this._vmInstances.set(id, kernel)
36 }
37 return kernel
38 }
39
40 async send (port, message) {
41 const vm = await this.getInstance(port)
42 const id = await this.generateID(port.id)
43 message._fromPort = id
44 vm.queue(message)
45 }
46
47 // given a port, wait untill its source contract has reached the threshold
48 // tick count
49 async wait (port, ticks) {
50 let kernel = await this.getInstance(port)
51 await kernel.wait(ticks)
52 return kernel
53 }
54
55 async createStateRoot (port, ticks) {
56 const kernel = await this.wait(port, ticks)
57 return this.graph.flush(kernel.state)
58 }
59
60 async generateID (port) {
61 let id = Buffer.concat([port.nonce, port.parent])
62 id = await crypto.subtle.digest('SHA-256', id)
63 return new Buffer(id).toString('hex')
64 }
65
66 addVM (type, vm) {
67 this._opts.VMs[type] = vm
68 }
69}
70

Built with git-ssb-web