git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 9b5545940cea05703845fc350781ee577ca2e326

Files: 9b5545940cea05703845fc350781ee577ca2e326 / index.js

7313 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 let code = create.data
130
131 // Inject metering
132 if (Utils.isWASMCode(code)) {
133 code = this.callHandler({ to: meteringContract, data: code }).returnValue
134 }
135
136 let address = Utils.newAccountAddress(create.from, code)
137
138 this.environment.addAccount(address.toString(), {
139 balance: create.value,
140 code: code
141 })
142
143 // Run code and take return value as contract code
144 code = this.callHandler({ from: create.from, to: address, gasLimit: create.gasLimit }).returnValue
145
146 this.environment.state.get(address.toString()).set('code', code)
147
148 return {
149 accountCreated: address
150 }
151 }
152
153 // run tx; the tx message handler
154 runTx (tx, environment = new Environment()) {
155 this.environment = environment
156
157 if (Buffer.isBuffer(tx) || typeof tx === 'string') {
158 tx = new Transaction(tx)
159 if (!tx.valid) {
160 throw new Error('Invalid transaction signature')
161 }
162 }
163
164 // look up sender
165 let fromAccount = this.environment.state.get(tx.from.toString())
166 if (!fromAccount) {
167 throw new Error('Sender account not found: ' + tx.from.toString())
168 }
169
170 if (fromAccount.get('nonce').gt(tx.nonce)) {
171 throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
172 }
173
174 fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))
175
176 // Special case: contract deployment
177 if (tx.to.isZero()) {
178 if (tx.data.length !== 0) {
179 console.log('This is a contract deployment transaction')
180
181 // FIXME: deduct fees
182
183 return this.createHandler({
184 from: tx.from,
185 gasLimit: tx.gasLimit,
186 value: tx.value,
187 data: tx.data
188 })
189 }
190 }
191
192 // deduct gasLimit * gasPrice from sender
193 if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
194 throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
195 }
196
197 fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))
198
199 let ret = this.callHandler({
200 to: tx.to,
201 from: tx.from,
202 gasLimit: tx.gasLimit,
203 value: tx.value,
204 data: tx.data
205 })
206
207 // refund gas
208 if (ret.executionOutcome === 1) {
209 fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
210 }
211
212 // save new state?
213
214 return {
215 returnValue: ret.returnValue,
216 gasLeft: ret.gasLeft,
217 logs: ret.logs
218 }
219 }
220
221 // run block; the block message handler
222 runBlock (block, environment = new Environment()) {
223 // verify block then run each tx
224 block.tx.forEach((tx) => {
225 this.runTx(tx, environment)
226 })
227 }
228
229 // run blockchain
230 // runBlockchain () {}
231}
232

Built with git-ssb-web