git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: 05bf86af31b825ac9b412fbc4b18522d2b40e829

Files: 05bf86af31b825ac9b412fbc4b18522d2b40e829 / index.js

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

Built with git-ssb-web