git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 3b07461593e97b8ecb99d055a38948670485d41e

Files: 3b07461593e97b8ecb99d055a38948670485d41e / index.js

9672 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 identityContract = new Address('0x0000000000000000000000000000000000000004')
29const meteringContract = new Address('0x000000000000000000000000000000000000000A')
30const transcompilerContract = new Address('0x000000000000000000000000000000000000000B')
31
32module.exports = class Kernel {
33 // runs some code in the VM
34 constructor (environment = new Environment()) {
35 this.environment = environment
36
37 this.environment.addAccount(identityContract, {})
38 this.environment.addAccount(meteringContract, {})
39 this.environment.addAccount(transcompilerContract, {})
40 }
41
42 // handles running code.
43 // NOTE: it assumes that wasm will raise an exception if something went wrong,
44 // otherwise execution succeeded
45 codeHandler (code, ethInterface = new Interface(new Environment())) {
46 const debugInterface = new DebugInterface(ethInterface.environment)
47 const module = WebAssembly.Module(code)
48 const imports = {
49 'ethereum': ethInterface.exportTable,
50 'debug': debugInterface.exportTable,
51
52 // export this for Rust
53 // FIXME: remove once Rust has proper imports, see https://github.com/ethereum/evm2.0-design/issues/15
54 'spectest': ethInterface.exportTable,
55
56 // export this for Binaryen
57 // FIXME: remove once C has proper imports, see https://github.com/ethereum/evm2.0-design/issues/16
58 'env': ethInterface.exportTable
59 }
60 // add shims
61 imports.ethereum.useGas = ethInterface.shims.exports.useGas
62 imports.ethereum.getGasLeft = ethInterface.shims.exports.getGasLeft
63
64 const instance = WebAssembly.Instance(module, imports)
65
66 ethInterface.setModule(instance)
67 debugInterface.setModule(instance)
68
69 if (instance.exports.main) {
70 instance.exports.main()
71 }
72 return instance
73 }
74
75 // loads code from the merkle trie and delegates the message
76 // Detects if code is EVM or WASM
77 // Detects if the code injection is needed
78 // Detects if transcompilation is needed
79 callHandler (call) {
80 // FIXME: this is here until these two contracts are compiled to WASM
81 // The two special contracts (precompiles now, but will be real ones later)
82 if (call.to.equals(meteringContract)) {
83 return Precompile.meteringInjector(call)
84 } else if (call.to.equals(transcompilerContract)) {
85 return Precompile.transcompiler(call)
86 } else if (call.to.equals(identityContract)) {
87 return Precompile.identity(call)
88 }
89
90 let account = this.environment.state.get(call.to.toString())
91 if (!account) {
92 throw new Error('Account not found: ' + call.to.toString())
93 }
94
95 let code = Uint8Array.from(account.get('code'))
96 if (code.length === 0) {
97 throw new Error('Contract not found')
98 }
99
100 if (!Utils.isWASMCode(code)) {
101 // throw new Error('Not an eWASM contract')
102
103 // Transcompile code
104 // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
105 code = this.callHandler({ from: Address.zero(), to: transcompilerContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
106
107 if (code[0] === 0) {
108 code = code.slice(1)
109 } else {
110 throw new Error('Transcompilation failed: ' + Buffer.from(code).slice(1).toString())
111 }
112 }
113
114 // creats a new Kernel
115 const environment = new Environment()
116 environment.parent = this
117
118 // copy the transaction details
119 environment.code = code
120 environment.address = call.to
121 // FIXME: make distinction between origin and caller
122 environment.origin = call.from
123 environment.caller = call.from
124 environment.callData = call.data
125 environment.callValue = call.value
126 environment.gasLeft = call.gasLimit
127
128 environment.callHandler = this.callHandler.bind(this)
129 environment.createHandler = this.createHandler.bind(this)
130
131 const kernel = new Kernel(environment)
132 kernel.codeHandler(code, new Interface(environment))
133
134 // self destructed
135 if (environment.selfDestruct) {
136 const balance = this.state.get(call.to.toString()).get('balance')
137 const beneficiary = this.state.get(environment.selfDestructAddress)
138 beneficiary.set('balance', beneficiary.get('balance').add(balance))
139 this.state.delete(call.to.toString())
140 }
141
142 // generate new stateroot
143 // this.environment.state.set(address, { stateRoot: stateRoot })
144
145 return {
146 executionOutcome: 1, // success
147 gasLeft: new U256(environment.gasLeft),
148 gasRefund: new U256(environment.gasRefund),
149 returnValue: environment.returnValue,
150 selfDestruct: environment.selfDestruct,
151 selfDestructAddress: environment.selfDestructAddress,
152 logs: environment.logs
153 }
154 }
155
156 createHandler (create) {
157 let code = create.data
158
159 // Inject metering
160 if (Utils.isWASMCode(code)) {
161 // FIXME: decide if these are the right values here: from: 0, gasLimit: 0, value: 0
162 code = this.callHandler({ from: Address.zero(), to: meteringContract, gasLimit: 0, value: new U256(0), data: code }).returnValue
163
164 if (code[0] === 0) {
165 code = code.slice(1)
166 } else {
167 throw new Error('Metering injection failed: ' + Buffer.from(code).slice(1).toString())
168 }
169 }
170
171 let address = Utils.newAccountAddress(create.from, code)
172
173 this.environment.addAccount(address.toString(), {
174 balance: create.value,
175 code: code
176 })
177
178 // Run code and take return value as contract code
179 // FIXME: decide if these are the right values here: value: 0, data: ''
180 code = this.callHandler({ from: create.from, to: address, gasLimit: create.gasLimit, value: new U256(0), data: new Uint8Array() }).returnValue
181
182 // FIXME: special handling for selfdestruct
183
184 this.environment.state.get(address.toString()).set('code', code)
185
186 return {
187 executionOutcome: 1, // success
188 gasLeft: new U256(this.environment.gasLeft),
189 gasRefund: new U256(this.environment.gasRefund),
190 accountCreated: address,
191 logs: this.environment.logs
192 }
193 }
194
195 // run tx; the tx message handler
196 runTx (tx, environment = new Environment()) {
197 this.environment = environment
198
199 if (Buffer.isBuffer(tx) || typeof tx === 'string') {
200 tx = new Transaction(tx)
201 if (!tx.valid) {
202 throw new Error('Invalid transaction signature')
203 }
204 }
205
206 // look up sender
207 let fromAccount = this.environment.state.get(tx.from.toString())
208 if (!fromAccount) {
209 throw new Error('Sender account not found: ' + tx.from.toString())
210 }
211
212 if (fromAccount.get('nonce').gt(tx.nonce)) {
213 throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
214 }
215
216 fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))
217
218 let isCreation = false
219
220 // Special case: contract deployment
221 if (tx.to.isZero() && (tx.data.length !== 0)) {
222 console.log('This is a contract deployment transaction')
223 isCreation = true
224 }
225
226 // This cost will not be refunded
227 let txCost = 21000 + (isCreation ? 32000 : 0)
228 tx.data.forEach((item) => {
229 if (item === 0) {
230 txCost += 4
231 } else {
232 txCost += 68
233 }
234 })
235
236 if (tx.gasLimit.lt(new U256(txCost))) {
237 throw new Error(`Minimum transaction gas limit not met: ${txCost}`)
238 }
239
240 if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
241 throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
242 }
243
244 // deduct gasLimit * gasPrice from sender
245 fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))
246
247 const handler = isCreation ? this.createHandler.bind(this) : this.callHandler.bind(this)
248 let ret = handler({
249 to: tx.to,
250 from: tx.from,
251 gasLimit: tx.gasLimit - txCost,
252 value: tx.value,
253 data: tx.data
254 })
255
256 // refund unused gas
257 if (ret.executionOutcome === 1) {
258 fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
259 }
260
261 // save new state?
262
263 return {
264 executionOutcome: ret.executionOutcome,
265 accountCreated: isCreation ? ret.accountCreated : undefined,
266 returnValue: isCreation ? undefined : ret.returnValue,
267 gasLeft: ret.gasLeft,
268 logs: ret.logs
269 }
270 }
271
272 // run block; the block message handler
273 runBlock (block, environment = new Environment()) {
274 // verify block then run each tx
275 block.tx.forEach((tx) => {
276 this.runTx(tx, environment)
277 })
278 }
279
280 // run blockchain
281 // runBlockchain () {}
282}
283

Built with git-ssb-web