-
Notifications
You must be signed in to change notification settings - Fork 746
/
evm.ts
458 lines (414 loc) · 12.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import {
Account,
Address,
BN,
generateAddress,
generateAddress2,
KECCAK256_NULL,
MAX_INTEGER,
} from 'ethereumjs-util'
import { Block } from '@ethereumjs/block'
import { ERROR, VmError } from '../exceptions'
import { StateManager } from '../state/index'
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'
/**
* 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?: Address
/**
* 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[]
/**
* A map from the accounts that have self-destructed to the addresses to send their funds to
*/
selfdestruct?: { [k: string]: Buffer }
/**
* Total amount of gas to be refunded from all nested calls.
*/
gasRefund?: BN
}
export interface NewContractEvent {
address: Address
// The deployment code
code: Buffer
}
export function OOGResult(gasLimit: BN): ExecResult {
return {
returnValue: Buffer.alloc(0),
gasUsed: gasLimit,
exceptionError: new VmError(ERROR.OUT_OF_GAS),
}
}
// CodeDeposit OOG Result
export function COOGResult(gasUsedCreateCode: BN): ExecResult {
return {
returnValue: Buffer.alloc(0),
gasUsed: gasUsedCreateCode,
exceptionError: new VmError(ERROR.CODESTORE_OUT_OF_GAS),
}
}
export function VmErrorResult(error: VmError, gasUsed: BN): ExecResult {
return {
returnValue: Buffer.alloc(0),
gasUsed: gasUsed,
exceptionError: error,
}
}
/**
* 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: StateManager
_tx: TxContext
_block: Block
/**
* Amount of gas to refund from deleting storage values
*/
_refund: BN
constructor(vm: any, txContext: TxContext, block: Block) {
this._vm = vm
this._state = this._vm.stateManager
this._tx = txContext
this._block = block
this._refund = new BN(0)
}
/**
* 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._vm._emit('beforeMessage', message)
await this._state.checkpoint()
let result
if (message.to) {
result = await this._executeCall(message)
} else {
result = await this._executeCreate(message)
}
// TODO: Move `gasRefund` to a tx-level result object
// instead of `ExecResult`.
result.execResult.gasRefund = this._refund.clone()
const err = result.execResult.exceptionError
if (err) {
if (this._vm._common.gteHardfork('homestead') || err.error != ERROR.CODESTORE_OUT_OF_GAS) {
result.execResult.logs = []
await this._state.revert()
} else {
// we are in chainstart and the error was the code deposit error
// we do like nothing happened.
await this._state.commit()
}
} else {
await this._state.commit()
}
await this._vm._emit('afterMessage', result)
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
let errorMessage
if (!message.delegatecall) {
try {
await this._addToBalance(toAccount, message)
} catch (e) {
errorMessage = e
}
}
// Load code
await this._loadCode(message)
// Exit early if there's no code or value transfer overflowed
if (!message.code || message.code.length === 0 || errorMessage) {
return {
gasUsed: new BN(0),
execResult: {
gasUsed: new BN(0),
exceptionError: errorMessage, // Only defined if addToBalance failed
returnValue: Buffer.alloc(0),
},
}
}
let result: ExecResult
if (message.isCompiled) {
result = await 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 && toAccount.nonce.gtn(0)) || !toAccount.codeHash.equals(KECCAK256_NULL)) {
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)
const newContractEvent: NewContractEvent = {
address: message.to,
code: message.code,
}
await this._vm._emit('newContract', newContractEvent)
toAccount = await this._state.getAccount(message.to)
// EIP-161 on account creation and CREATE execution
if (this._vm._common.gteHardfork('spuriousDragon')) {
toAccount.nonce.iaddn(1)
}
// Add tx value to the `to` account
let errorMessage
try {
await this._addToBalance(toAccount, message)
} catch (e) {
errorMessage = e
}
// Exit early if there's no contract code or value transfer overflowed
if (!message.code || message.code.length === 0 || errorMessage) {
return {
gasUsed: new BN(0),
createdAddress: message.to,
execResult: {
gasUsed: new BN(0),
exceptionError: errorMessage, // only defined if addToBalance failed
returnValue: Buffer.alloc(0),
},
}
}
let result = await this.runInterpreter(message)
// fee for size of the return value
let totalGas = result.gasUsed
let returnFee = new BN(0)
if (!result.exceptionError) {
returnFee = new BN(result.returnValue.length).imuln(
this._vm._common.param('gasPrices', 'createData')
)
totalGas = totalGas.add(returnFee)
}
// Check for SpuriousDragon EIP-170 code size limit
let allowedCodeSize = true
if (
this._vm._common.gteHardfork('spuriousDragon') &&
result.returnValue.length > this._vm._common.param('vm', 'maxCodeSize')
) {
allowedCodeSize = false
}
// If enough gas and allowed code size
if (
totalGas.lte(message.gasLimit) &&
(this._vm._allowUnlimitedContractSize || allowedCodeSize)
) {
result.gasUsed = totalGas
} else {
if (this._vm._common.gteHardfork('homestead')) {
result = { ...result, ...OOGResult(message.gasLimit) }
} else {
// we are in Frontier
if (totalGas.sub(returnFee).lte(message.gasLimit)) {
// we cannot pay the code deposit fee (but the deposit code actually did run)
result = { ...result, ...COOGResult(totalGas.sub(returnFee)) }
} 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 || Address.zero(),
caller: message.caller || Address.zero(),
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 || Address.zero(),
block: this._block || new Block(),
contract: await this._state.getAccount(message.to || Address.zero()),
codeAddress: message.codeAddress,
}
const eei = new EEI(env, this._state, this, this._vm._common, message.gasLimit.clone())
if (message.selfdestruct) {
eei._result.selfdestruct = message.selfdestruct
}
const oldRefund = this._refund.clone()
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: [],
selfdestruct: {},
}
// Revert gas refund if message failed
this._refund = oldRefund
}
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: Address): PrecompileFunc {
return getPrecompile(address, this._vm._common)
}
/**
* Executes a precompiled contract with given data and gas limit.
*/
runPrecompile(
code: PrecompileFunc,
data: Buffer,
gasLimit: BN
): Promise<ExecResult> | ExecResult {
if (typeof code !== 'function') {
throw new Error('Invalid precompile')
}
const opts = {
data,
gasLimit,
_common: this._vm._common,
_VM: this._vm,
}
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<Address> {
let addr
if (message.salt) {
addr = generateAddress2(message.caller.buf, message.salt, message.code as Buffer)
} else {
const acc = await this._state.getAccount(message.caller)
const newNonce = acc.nonce.subn(1)
addr = generateAddress(message.caller.buf, newNonce.toArrayLike(Buffer))
}
return new Address(addr)
}
async _reduceSenderBalance(account: Account, message: Message): Promise<void> {
account.balance.isub(message.value)
return this._state.putAccount(message.caller, account)
}
async _addToBalance(toAccount: Account, message: Message): Promise<void> {
const newBalance = toAccount.balance.add(message.value)
if (newBalance.gt(MAX_INTEGER)) {
throw new VmError(ERROR.VALUE_OVERFLOW)
}
toAccount.balance = newBalance
// putAccount as the nonce may have changed for contract creation
return this._state.putAccount(message.to, toAccount)
}
async _touchAccount(address: Address): Promise<void> {
const account = await this._state.getAccount(address)
return this._state.putAccount(address, account)
}
}