git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: c9ac540197b2a640dfb17a9bacf432e75ebaa0c0

Files: c9ac540197b2a640dfb17a9bacf432e75ebaa0c0 / index.js

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

Built with git-ssb-web