-
Notifications
You must be signed in to change notification settings - Fork 759
/
evm.ts
381 lines (343 loc) · 10.8 KB
/
evm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import BN = require('bn.js')
import {
generateAddress,
generateAddress2,
KECCAK256_NULL,
MAX_INTEGER,
toBuffer,
zeros,
} from 'ethereumjs-util'
import Account from 'ethereumjs-account'
import { ERROR, VmError } from '../exceptions'
import PStateManager from '../state/promisified'
import { getPrecompile, PrecompileFunc } from './precompiles'
import TxContext from './txContext'
import Message from './message'
import EEI from './eei'
import { default as Interpreter, InterpreterOpts, RunState } from './interpreter'
const Block = require('ethereumjs-block')
/**
* Result of executing a message via the [[EVM]].
*/
export interface EVMResult {
/**
* Amount of gas used by the transaction
*/
gasUsed: BN
/**
* Address of created account durint transaction, if any
*/
createdAddress?: Buffer
/**
* Contains the results from running the code, if any, as described in [[runCode]]
*/
execResult: ExecResult
}
/**
* Result of executing a call via the [[EVM]].
*/
export interface ExecResult {
runState?: RunState
/**
* Description of the exception, if any occured
*/
exceptionError?: VmError
/**
* Amount of gas left
*/
gas?: BN
/**
* Amount of gas the code used to run
*/
gasUsed: BN
/**
* Return value from the contract
*/
returnValue: Buffer
/**
* Array of logs that the contract emitted
*/
logs?: any[]
/**
* Amount of gas to refund from deleting storage values
*/
gasRefund?: BN
/**
* A map from the accounts that have self-destructed to the addresses to send their funds to
*/
selfdestruct?: { [k: string]: Buffer }
}
export function OOGResult(gasLimit: BN): ExecResult {
return {
returnValue: Buffer.alloc(0),
gasUsed: gasLimit,
exceptionError: new VmError(ERROR.OUT_OF_GAS),
}
}
/**
* EVM is responsible for executing an EVM message fully
* (including any nested calls and creates), processing the results
* and storing them to state (or discarding changes in case of exceptions).
* @ignore
*/
export default class EVM {
_vm: any
_state: PStateManager
_tx: TxContext
_block: any
constructor(vm: any, txContext: TxContext, block: any) {
this._vm = vm
this._state = new PStateManager(this._vm.stateManager)
this._tx = txContext
this._block = block
}
/**
* Executes an EVM message, determining whether it's a call or create
* based on the `to` address. It checkpoints the state and reverts changes
* if an exception happens during the message execution.
*/
async executeMessage(message: Message): Promise<EVMResult> {
await this._state.checkpoint()
let result
if (message.to) {
result = await this._executeCall(message)
} else {
result = await this._executeCreate(message)
}
const err = result.execResult.exceptionError
if (err) {
result.execResult.logs = []
await this._state.revert()
if (message.isCompiled) {
// Empty precompiled contracts need to be deleted even in case of OOG
// because the bug in both Geth and Parity led to deleting RIPEMD precompiled in this case
// see https://github.com/ethereum/go-ethereum/pull/3341/files#diff-2433aa143ee4772026454b8abd76b9dd
// We mark the account as touched here, so that is can be removed among other touched empty accounts (after tx finalization)
if (err.error === ERROR.OUT_OF_GAS) {
await this._touchAccount(message.to)
}
}
} else {
await this._state.commit()
}
return result
}
async _executeCall(message: Message): Promise<EVMResult> {
const account = await this._state.getAccount(message.caller)
// Reduce tx value from sender
if (!message.delegatecall) {
await this._reduceSenderBalance(account, message)
}
// Load `to` account
const toAccount = await this._state.getAccount(message.to)
// Add tx value to the `to` account
if (!message.delegatecall) {
await this._addToBalance(toAccount, message)
}
// Load code
await this._loadCode(message)
if (!message.code || message.code.length === 0) {
return {
gasUsed: new BN(0),
execResult: {
gasUsed: new BN(0),
returnValue: Buffer.alloc(0),
},
}
}
let result: ExecResult
if (message.isCompiled) {
result = this.runPrecompile(message.code as PrecompileFunc, message.data, message.gasLimit)
} else {
result = await this.runInterpreter(message)
}
return {
gasUsed: result.gasUsed,
execResult: result,
}
}
async _executeCreate(message: Message): Promise<EVMResult> {
const account = await this._state.getAccount(message.caller)
// Reduce tx value from sender
await this._reduceSenderBalance(account, message)
message.code = message.data
message.data = Buffer.alloc(0)
message.to = await this._generateAddress(message)
let toAccount = await this._state.getAccount(message.to)
// Check for collision
if (
(toAccount.nonce && new BN(toAccount.nonce).gtn(0)) ||
toAccount.codeHash.compare(KECCAK256_NULL) !== 0
) {
return {
gasUsed: message.gasLimit,
createdAddress: message.to,
execResult: {
returnValue: Buffer.alloc(0),
exceptionError: new VmError(ERROR.CREATE_COLLISION),
gasUsed: message.gasLimit,
},
}
}
await this._state.clearContractStorage(message.to)
await this._vm._emit('newContract', {
address: message.to,
code: message.code,
})
toAccount = await this._state.getAccount(message.to)
toAccount.nonce = new BN(toAccount.nonce).addn(1).toArrayLike(Buffer)
// Add tx value to the `to` account
await this._addToBalance(toAccount, message)
if (!message.code || message.code.length === 0) {
return {
gasUsed: new BN(0),
createdAddress: message.to,
execResult: {
gasUsed: new BN(0),
returnValue: Buffer.alloc(0),
},
}
}
let result = await this.runInterpreter(message)
// fee for size of the return value
let totalGas = result.gasUsed
if (!result.exceptionError) {
const returnFee = new BN(
result.returnValue.length * this._vm._common.param('gasPrices', 'createData'),
)
totalGas = totalGas.add(returnFee)
}
// if not enough gas
if (
totalGas.lte(message.gasLimit) &&
(this._vm.allowUnlimitedContractSize || result.returnValue.length <= 24576)
) {
result.gasUsed = totalGas
} else {
result = { ...result, ...OOGResult(message.gasLimit) }
}
// Save code if a new contract was created
if (!result.exceptionError && result.returnValue && result.returnValue.toString() !== '') {
await this._state.putContractCode(message.to, result.returnValue)
}
return {
gasUsed: result.gasUsed,
createdAddress: message.to,
execResult: result,
}
}
/**
* Starts the actual bytecode processing for a CALL or CREATE, providing
* it with the [[EEI]].
*/
async runInterpreter(message: Message, opts: InterpreterOpts = {}): Promise<ExecResult> {
const env = {
blockchain: this._vm.blockchain, // Only used in BLOCKHASH
address: message.to || zeros(32),
caller: message.caller || zeros(32),
callData: message.data || Buffer.from([0]),
callValue: message.value || new BN(0),
code: message.code as Buffer,
isStatic: message.isStatic || false,
depth: message.depth || 0,
gasPrice: this._tx.gasPrice,
origin: this._tx.origin || message.caller || zeros(32),
block: this._block || new Block(),
contract: await this._state.getAccount(message.to || zeros(32)),
}
const eei = new EEI(env, this._state, this, this._vm._common, message.gasLimit.clone())
if (message.selfdestruct) {
eei._result.selfdestruct = message.selfdestruct
}
const interpreter = new Interpreter(this._vm, eei)
const interpreterRes = await interpreter.run(message.code as Buffer, opts)
let result = eei._result
let gasUsed = message.gasLimit.sub(eei._gasLeft)
if (interpreterRes.exceptionError) {
if (interpreterRes.exceptionError.error !== ERROR.REVERT) {
gasUsed = message.gasLimit
}
// Clear the result on error
result = {
...result,
logs: [],
gasRefund: new BN(0),
selfdestruct: {},
}
}
return {
...result,
runState: {
...interpreterRes.runState!,
...result,
...eei._env,
},
exceptionError: interpreterRes.exceptionError,
gas: eei._gasLeft,
gasUsed,
returnValue: result.returnValue ? result.returnValue : Buffer.alloc(0),
}
}
/**
* Returns code for precompile at the given address, or undefined
* if no such precompile exists.
*/
getPrecompile(address: Buffer): PrecompileFunc {
return getPrecompile(address.toString('hex'))
}
/**
* Executes a precompiled contract with given data and gas limit.
*/
runPrecompile(code: PrecompileFunc, data: Buffer, gasLimit: BN): ExecResult {
if (typeof code !== 'function') {
throw new Error('Invalid precompile')
}
const opts = {
data,
gasLimit,
_common: this._vm._common,
}
return code(opts)
}
async _loadCode(message: Message): Promise<void> {
if (!message.code) {
const precompile = this.getPrecompile(message.codeAddress)
if (precompile) {
message.code = precompile
message.isCompiled = true
} else {
message.code = await this._state.getContractCode(message.codeAddress)
message.isCompiled = false
}
}
}
async _generateAddress(message: Message): Promise<Buffer> {
let addr
if (message.salt) {
addr = generateAddress2(message.caller, message.salt, message.code as Buffer)
} else {
const acc = await this._state.getAccount(message.caller)
const newNonce = new BN(acc.nonce).subn(1)
addr = generateAddress(message.caller, newNonce.toArrayLike(Buffer))
}
return addr
}
async _reduceSenderBalance(account: Account, message: Message): Promise<void> {
const newBalance = new BN(account.balance).sub(message.value)
account.balance = toBuffer(newBalance)
return this._state.putAccount(toBuffer(message.caller), account)
}
async _addToBalance(toAccount: Account, message: Message): Promise<void> {
const newBalance = new BN(toAccount.balance).add(message.value)
if (newBalance.gt(MAX_INTEGER)) {
throw new Error('Value overflow')
}
toAccount.balance = toBuffer(newBalance)
// putAccount as the nonce may have changed for contract creation
return this._state.putAccount(toBuffer(message.to), toAccount)
}
async _touchAccount(address: Buffer): Promise<void> {
const acc = await this._state.getAccount(address)
return this._state.putAccount(address, acc)
}
}