git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 1039324df6ed695b396944c8d6f5f4157f3bf6ce

Files: 1039324df6ed695b396944c8d6f5f4157f3bf6ce / index.js

7249 bytesRaw
1/**
2 * This implements the Ethereum Kernel
3 * Kernels must implement two methods `codeHandler` and `callHandler` (and `linkHandler` for sharding)
4 * The Kernel Contract handles the following
5 * - Interprocess communications
6 * - Intializing the VM and exposes ROM to it (codeHandler)
7 * - Expose namespace which VM instance exists and Intializes the Environment (callHandler)
8 * - Provides some built in contract (runTx, runBlock)
9 * - Provides resource sharing and limiting via gas
10 *
11 * All State should be stored in the Environment.
12 *
13 */
14
15// The Kernel Exposes this Interface to VM instances it makes
16const Interface = require('./interface.js')
17
18// The Kernel Stores all of its state in the Environment. The Interface is used
19// to by the VM to retrive infromation from the Environment.
20const Environment = require('./environment.js')
21const DebugInterface = require('./debugInterface.js')
22const Address = require('./address.js')
23const U256 = require('./u256.js')
24const Utils = require('./utils.js')
25const Transaction = require('./transaction.js')
26const Precompile = require('./precompile.js')
27
28const meteringContract = new Address('0x000000000000000000000000000000000000000A')
29const transcompilerContract = new Address('0x000000000000000000000000000000000000000B')
30
31module.exports = class Kernel {
32 // runs some code in the VM
33 constructor (environment = new Environment()) {
34 this.environment = environment
35 }
36
37 // handles running code.
38 // NOTE: it assumes that wasm will raise an exception if something went wrong,
39 // otherwise execution succeeded
40 codeHandler (code, ethInterface = new Interface(new Environment())) {
41 const debugInterface = new DebugInterface(ethInterface.environment)
42
43 const instance = Wasm.instantiateModule(code, {
44 'ethereum': ethInterface.exportTable,
45 'debug': debugInterface.exportTable,
46
47 // export this for Rust
48 // FIXME: remove once Rust has proper imports, see https://github.com/ethereum/evm2.0-design/issues/15
49 'spectest': ethInterface.exportTable,
50
51 // export this for Binaryen
52 // FIXME: remove once C has proper imports, see https://github.com/ethereum/evm2.0-design/issues/16
53 'env': ethInterface.exportTable
54 })
55
56 ethInterface.setModule(instance)
57 debugInterface.setModule(instance)
58
59 if (instance.exports.main) {
60 instance.exports.main()
61 }
62 return instance
63 }
64
65 // loads code from the merkle trie and delegates the message
66 // Detects if code is EVM or WASM
67 // Detects if the code injection is needed
68 // Detects if transcompilation is needed
69 callHandler (call) {
70 // FIXME: this is here until these two contracts are compiled to WASM
71 // The two special contracts (precompiles now, but will be real ones later)
72 if (call.to.equals(meteringContract)) {
73 return Precompile.meteringInjector(call)
74 } else if (call.to.equals(transcompilerContract)) {
75 return Precompile.transcompiler(call)
76 }
77
78 let account = this.environment.state.get(call.to.toString())
79 if (!account) {
80 throw new Error('Account not found: ' + call.to.toString())
81 }
82
83 let code = Uint8Array.from(account.get('code'))
84 if (code.length === 0) {
85 throw new Error('Contract not found')
86 }
87
88 if (!Utils.isWASMCode(code)) {
89 // throw new Error('Not an eWASM contract')
90
91 // Transcompile code
92 code = this.callHandler({ to: transcompilerContract, data: code }).returnValue
93 }
94
95 // creats a new Kernel
96 const environment = new Environment()
97 environment.parent = this
98
99 // copy the transaction details
100 environment.code = code
101 environment.address = call.to
102 // FIXME: make distinction between origin and caller
103 environment.origin = call.from
104 environment.caller = call.from
105 environment.callData = call.data
106 environment.callValue = call.value
107 environment.gasLeft = call.gasLimit
108
109 // environment.setCallHandler(this.callHandler)
110 // environment.setCreateHandler(this.createHandler)
111
112 const kernel = new Kernel(this, environment)
113 kernel.codeHandler(code, new Interface(environment))
114
115 // generate new stateroot
116 // this.environment.state.set(address, { stateRoot: stateRoot })
117
118 return {
119 executionOutcome: 1, // success
120 gasLeft: new U256(environment.gasLeft),
121 gasRefund: new U256(environment.gasRefund),
122 returnValue: environment.returnValue,
123 selfDestructAddress: environment.selfDestructAddress,
124 logs: environment.logs
125 }
126 }
127
128 createHandler (create) {
129 // Inject metering
130 const code = this.callHandler({ to: meteringContract, data: code }).returnValue
131
132 let address = Utils.newAccountAddress(create.from, code)
133
134 this.environment.addAccount(address.toString(), {
135 balance: create.value,
136 code: code
137 })
138
139 // Run code and take return value as contract code
140 code = this.callHandler({ from: create.from, to: address, gasLimit: create.gasLimit }).returnValue
141
142 this.environment.state.get(address.toString()).set('code', code)
143
144 return {
145 accountCreated: address
146 }
147 }
148
149 // run tx; the tx message handler
150 runTx (tx, environment = new Environment()) {
151 this.environment = environment
152
153 if (Buffer.isBuffer(tx) || typeof tx === 'string') {
154 tx = new Transaction(tx)
155 if (!tx.valid) {
156 throw new Error('Invalid transaction signature')
157 }
158 }
159
160 // look up sender
161 let fromAccount = this.environment.state.get(tx.from.toString())
162 if (!fromAccount) {
163 throw new Error('Sender account not found: ' + tx.from.toString())
164 }
165
166 if (fromAccount.get('nonce').gt(tx.nonce)) {
167 throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
168 }
169
170 fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))
171
172 // Special case: contract deployment
173 if (tx.to.isZero()) {
174 if (tx.data.length !== 0) {
175 console.log('This is a contract deployment transaction')
176
177 // FIXME: deduct fees
178
179 return this.createHandler({
180 from: tx.from,
181 gasLimit: tx.gasLimit,
182 value: tx.value,
183 data: tx.data
184 })
185 }
186 }
187
188 // deduct gasLimit * gasPrice from sender
189 if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
190 throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
191 }
192
193 fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))
194
195 let ret = this.callHandler({
196 to: tx.to,
197 from: tx.from,
198 gasLimit: tx.gasLimit,
199 value: tx.value,
200 data: tx.data
201 })
202
203 // refund gas
204 if (ret.executionOutcome === 1) {
205 fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
206 }
207
208 // save new state?
209
210 return {
211 returnValue: ret.returnValue,
212 gasLeft: ret.gasLeft,
213 logs: ret.logs
214 }
215 }
216
217 // run block; the block message handler
218 runBlock (block, environment = new Environment()) {
219 // verify block then run each tx
220 block.tx.forEach((tx) => {
221 this.runTx(tx, environment)
222 })
223 }
224
225 // run blockchain
226 // runBlockchain () {}
227}
228

Built with git-ssb-web