git ssb

0+

wanderer🌟 / js-primea-hypervisor



Tree: d40898a1c0e4f37c6b28da6da6646db86398ebcb

Files: d40898a1c0e4f37c6b28da6da6646db86398ebcb / index.js

6806 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(callHandler)
110
111 const kernel = new Kernel(this, environment)
112 kernel.codeHandler(code, new Interface(environment))
113
114 // generate new stateroot
115 // this.environment.state.set(address, { stateRoot: stateRoot })
116
117 return {
118 executionOutcome: 1, // success
119 gasLeft: new U256(environment.gasLeft),
120 gasRefund: new U256(environment.gasRefund),
121 returnValue: environment.returnValue,
122 selfDestructAddress: environment.selfDestructAddress,
123 logs: environment.logs
124 }
125 }
126
127 // run tx; the tx message handler
128 runTx (tx, environment = new Environment()) {
129 this.environment = environment
130
131 if (Buffer.isBuffer(tx) || typeof tx === 'string') {
132 tx = new Transaction(tx)
133 if (!tx.valid) {
134 throw new Error('Invalid transaction signature')
135 }
136 }
137
138 // look up sender
139 let fromAccount = this.environment.state.get(tx.from.toString())
140 if (!fromAccount) {
141 throw new Error('Sender account not found: ' + tx.from.toString())
142 }
143
144 if (fromAccount.get('nonce').gt(tx.nonce)) {
145 throw new Error(`Invalid nonce: ${fromAccount.get('nonce')} > ${tx.nonce}`)
146 }
147
148 fromAccount.set('nonce', fromAccount.get('nonce').add(new U256(1)))
149
150 // Special case: contract deployment
151 if (tx.to.isZero()) {
152 if (tx.data.length !== 0) {
153 console.log('This is a contract deployment transaction')
154
155 // Inject metering
156 const code = this.callHandler({ to: meteringContract, data: tx.data }).returnValue
157
158 let address = Utils.newAccountAddress(tx.from, code)
159
160 this.environment.addAccount(address.toString(), {
161 balance: tx.value,
162 code: code
163 })
164
165 // FIXME: deduct fees
166
167 return {
168 accountCreated: address
169 }
170 }
171 }
172
173 // deduct gasLimit * gasPrice from sender
174 if (fromAccount.get('balance').lt(tx.gasLimit.mul(tx.gasPrice))) {
175 throw new Error(`Insufficient account balance: ${fromAccount.get('balance').toString()} < ${tx.gasLimit.mul(tx.gasPrice).toString()}`)
176 }
177
178 fromAccount.set('balance', fromAccount.get('balance').sub(tx.gasLimit.mul(tx.gasPrice)))
179
180 let ret = this.callHandler({
181 to: tx.to,
182 from: tx.from,
183 gasLimit: tx.gasLimit,
184 value: tx.value,
185 data: tx.data
186 })
187
188 // refund gas
189 if (ret.executionOutcome === 1) {
190 fromAccount.set('balance', fromAccount.get('balance').add(tx.gasPrice.mul(ret.gasLeft.add(ret.gasRefund))))
191 }
192
193 // save new state?
194
195 return {
196 returnValue: ret.returnValue,
197 gasLeft: ret.gasLeft,
198 logs: ret.logs
199 }
200 }
201
202 // run block; the block message handler
203 runBlock (block, environment = new Environment()) {
204 // verify block then run each tx
205 block.tx.forEach((tx) => {
206 this.runTx(tx, environment)
207 })
208 }
209
210 // run blockchain
211 // runBlockchain () {}
212}
213

Built with git-ssb-web