git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 643fe1d2f37714b0ada02a671a4c74924ce8437e

Files: 643fe1d2f37714b0ada02a671a4c74924ce8437e / index.js

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

Built with git-ssb-web