-
Notifications
You must be signed in to change notification settings - Fork 791
/
Copy patheei.ts
707 lines (621 loc) · 19.1 KB
/
eei.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import { debug as createDebugLogger } from 'debug'
import { Account, Address, BN, MAX_UINT64 } from 'ethereumjs-util'
import { Block } from '@ethereumjs/block'
import Blockchain from '@ethereumjs/blockchain'
import Common, { ConsensusAlgorithm } from '@ethereumjs/common'
import { StateManager } from '../state/index'
import { VmError, ERROR } from '../exceptions'
import Message from './message'
import EVM, { EVMResult } from './evm'
import { Log } from './types'
import { TransientStorage } from '../state'
const debugGas = createDebugLogger('vm:eei:gas')
function trap(err: ERROR) {
throw new VmError(err)
}
const MASK_160 = new BN(1).shln(160).subn(1)
function addressToBuffer(address: BN) {
if (Buffer.isBuffer(address)) return address
return address.and(MASK_160).toArrayLike(Buffer, 'be', 20)
}
/**
* Environment data which is made available to EVM bytecode.
*/
export interface Env {
blockchain: Blockchain
address: Address
caller: Address
callData: Buffer
callValue: BN
code: Buffer
isStatic: boolean
depth: number
gasPrice: BN
origin: Address
block: Block
contract: Account
// Different than address for DELEGATECALL and CALLCODE
codeAddress: Address
}
/**
* Immediate (unprocessed) result of running an EVM bytecode.
*/
export interface RunResult {
logs: Log[]
returnValue?: Buffer
/**
* A map from the accounts that have self-destructed to the addresses to send their funds to
*/
selfdestruct: { [k: string]: Buffer }
}
/**
* External interface made available to EVM bytecode. Modeled after
* the ewasm EEI [spec](https://github.com/ewasm/design/blob/master/eth_interface.md).
* It includes methods for accessing/modifying state, calling or creating contracts, access
* to environment data among other things.
* The EEI instance also keeps artifacts produced by the bytecode such as logs
* and to-be-selfdestructed addresses.
*/
export default class EEI {
_env: Env
_result: RunResult
_state: StateManager
_evm: EVM
_lastReturned: Buffer
_common: Common
_gasLeft: BN
_transientStorage: TransientStorage
constructor(
env: Env,
state: StateManager,
evm: EVM,
common: Common,
gasLeft: BN,
transientStorage: TransientStorage
) {
this._env = env
this._state = state
this._evm = evm
this._lastReturned = Buffer.alloc(0)
this._common = common
this._gasLeft = gasLeft
this._result = {
logs: [],
returnValue: undefined,
selfdestruct: {},
}
this._transientStorage = transientStorage
}
/**
* Subtracts an amount from the gas counter.
* @param amount - Amount of gas to consume
* @param context - Usage context for debugging
* @throws if out of gas
*/
useGas(amount: BN, context?: string): void {
this._gasLeft.isub(amount)
if (this._evm._vm.DEBUG) {
debugGas(`${context ? context + ': ' : ''}used ${amount} gas (-> ${this._gasLeft})`)
}
if (this._gasLeft.ltn(0)) {
this._gasLeft = new BN(0)
trap(ERROR.OUT_OF_GAS)
}
}
/**
* Adds a positive amount to the gas counter.
* @param amount - Amount of gas refunded
* @param context - Usage context for debugging
*/
refundGas(amount: BN, context?: string): void {
if (this._evm._vm.DEBUG) {
debugGas(`${context ? context + ': ' : ''}refund ${amount} gas (-> ${this._evm._refund})`)
}
this._evm._refund.iadd(amount)
}
/**
* Reduces amount of gas to be refunded by a positive value.
* @param amount - Amount to subtract from gas refunds
* @param context - Usage context for debugging
*/
subRefund(amount: BN, context?: string): void {
if (this._evm._vm.DEBUG) {
debugGas(`${context ? context + ': ' : ''}sub gas refund ${amount} (-> ${this._evm._refund})`)
}
this._evm._refund.isub(amount)
if (this._evm._refund.ltn(0)) {
this._evm._refund = new BN(0)
trap(ERROR.REFUND_EXHAUSTED)
}
}
/**
* Increments the internal gasLeft counter. Used for adding callStipend.
* @param amount - Amount to add
*/
addStipend(amount: BN): void {
if (this._evm._vm.DEBUG) {
debugGas(`add stipend ${amount} (-> ${this._gasLeft})`)
}
this._gasLeft.iadd(amount)
}
/**
* Returns address of currently executing account.
*/
getAddress(): Address {
return this._env.address
}
/**
* Returns balance of the given account.
* @param address - Address of account
*/
async getExternalBalance(address: Address): Promise<BN> {
// shortcut if current account
if (address.equals(this._env.address)) {
return this._env.contract.balance
}
// otherwise load account then return balance
const account = await this._state.getAccount(address)
return account.balance
}
/**
* Returns balance of self.
*/
getSelfBalance(): BN {
return this._env.contract.balance
}
/**
* Returns caller address. This is the address of the account
* that is directly responsible for this execution.
*/
getCaller(): BN {
return new BN(this._env.caller.buf)
}
/**
* Returns the deposited value by the instruction/transaction
* responsible for this execution.
*/
getCallValue(): BN {
return new BN(this._env.callValue)
}
/**
* Returns input data in current environment. This pertains to the input
* data passed with the message call instruction or transaction.
*/
getCallData(): Buffer {
return this._env.callData
}
/**
* Returns size of input data in current environment. This pertains to the
* input data passed with the message call instruction or transaction.
*/
getCallDataSize(): BN {
return new BN(this._env.callData.length)
}
/**
* Returns the size of code running in current environment.
*/
getCodeSize(): BN {
return new BN(this._env.code.length)
}
/**
* Returns the code running in current environment.
*/
getCode(): Buffer {
return this._env.code
}
/**
* Returns true if the current call must be executed statically.
*/
isStatic(): boolean {
return this._env.isStatic
}
/**
* Get size of an account’s code.
* @param address - Address of account
*/
async getExternalCodeSize(address: BN): Promise<BN> {
const addr = new Address(addressToBuffer(address))
const code = await this._state.getContractCode(addr)
return new BN(code.length)
}
/**
* Returns code of an account.
* @param address - Address of account
*/
async getExternalCode(address: BN): Promise<Buffer> {
const addr = new Address(addressToBuffer(address))
return this._state.getContractCode(addr)
}
/**
* Returns size of current return data buffer. This contains the return data
* from the last executed call, callCode, callDelegate, callStatic or create.
* Note: create only fills the return data buffer in case of a failure.
*/
getReturnDataSize(): BN {
return new BN(this._lastReturned.length)
}
/**
* Returns the current return data buffer. This contains the return data
* from last executed call, callCode, callDelegate, callStatic or create.
* Note: create only fills the return data buffer in case of a failure.
*/
getReturnData(): Buffer {
return this._lastReturned
}
/**
* Returns price of gas in current environment.
*/
getTxGasPrice(): BN {
return this._env.gasPrice
}
/**
* Returns the execution's origination address. This is the
* sender of original transaction; it is never an account with
* non-empty associated code.
*/
getTxOrigin(): BN {
return new BN(this._env.origin.buf)
}
/**
* Returns the block’s number.
*/
getBlockNumber(): BN {
return this._env.block.header.number
}
/**
* Returns the block's beneficiary address.
*/
getBlockCoinbase(): BN {
let coinbase: Address
if (this._common.consensusAlgorithm() === ConsensusAlgorithm.Clique) {
// Backwards-compatibilty check
// TODO: can be removed along VM v5 release
if ('cliqueSigner' in this._env.block.header) {
coinbase = this._env.block.header.cliqueSigner()
} else {
coinbase = Address.zero()
}
} else {
coinbase = this._env.block.header.coinbase
}
return new BN(coinbase.toBuffer())
}
/**
* Returns the block's timestamp.
*/
getBlockTimestamp(): BN {
return this._env.block.header.timestamp
}
/**
* Returns the block's difficulty.
*/
getBlockDifficulty(): BN {
return this._env.block.header.difficulty
}
/**
* Returns the block's prevRandao field.
*/
getBlockPrevRandao(): BN {
return new BN(this._env.block.header.prevRandao)
}
/**
* Returns the block's gas limit.
*/
getBlockGasLimit(): BN {
return this._env.block.header.gasLimit
}
/**
* Returns the chain ID for current chain. Introduced for the
* CHAINID opcode proposed in [EIP-1344](https://eips.ethereum.org/EIPS/eip-1344).
*/
getChainId(): BN {
return this._common.chainIdBN()
}
/**
* Returns the Base Fee of the block as proposed in [EIP-3198](https;//eips.etheruem.org/EIPS/eip-3198)
*/
getBlockBaseFee(): BN {
const baseFee = this._env.block.header.baseFeePerGas
if (baseFee === undefined) {
// Sanity check
throw new Error('Block has no Base Fee')
}
return baseFee
}
/**
* Returns Gets the hash of one of the 256 most recent complete blocks.
* @param num - Number of block
*/
async getBlockHash(num: BN): Promise<BN> {
const block = await this._env.blockchain.getBlock(num)
return new BN(block.hash())
}
/**
* Store 256-bit a value in memory to persistent storage.
*/
async storageStore(key: Buffer, value: Buffer): Promise<void> {
await this._state.putContractStorage(this._env.address, key, value)
const account = await this._state.getAccount(this._env.address)
this._env.contract = account
}
/**
* Loads a 256-bit value to memory from persistent storage.
* @param key - Storage key
* @param original - If true, return the original storage value (default: false)
*/
async storageLoad(key: Buffer, original = false): Promise<Buffer> {
if (original) {
return this._state.getOriginalContractStorage(this._env.address, key)
} else {
return this._state.getContractStorage(this._env.address, key)
}
}
/**
* Store 256-bit a value in memory to transient storage.
* @param key - Storage key
* @param value - Storage value
*/
transientStorageStore(key: Buffer, value: Buffer): void {
return this._transientStorage.put(this._env.address, key, value)
}
/**
* Loads a 256-bit value to memory from transient storage.
* @param key - Storage key
*/
transientStorageLoad(key: Buffer): Buffer {
return this._transientStorage.get(this._env.address, key)
}
/**
* Returns the current gasCounter.
*/
getGasLeft(): BN {
return this._gasLeft.clone()
}
/**
* Set the returning output data for the execution.
* @param returnData - Output data to return
*/
finish(returnData: Buffer): void {
this._result.returnValue = returnData
trap(ERROR.STOP)
}
/**
* Set the returning output data for the execution. This will halt the
* execution immediately and set the execution result to "reverted".
* @param returnData - Output data to return
*/
revert(returnData: Buffer): void {
this._result.returnValue = returnData
trap(ERROR.REVERT)
}
/**
* Mark account for later deletion and give the remaining balance to the
* specified beneficiary address. This will cause a trap and the
* execution will be aborted immediately.
* @param toAddress - Beneficiary address
*/
async selfDestruct(toAddress: Address): Promise<void> {
return this._selfDestruct(toAddress)
}
async _selfDestruct(toAddress: Address): Promise<void> {
// only add to refund if this is the first selfdestruct for the address
if (!this._result.selfdestruct[this._env.address.buf.toString('hex')]) {
this.refundGas(new BN(this._common.param('gasPrices', 'selfdestructRefund')))
}
this._result.selfdestruct[this._env.address.buf.toString('hex')] = toAddress.buf
// Add to beneficiary balance
const toAccount = await this._state.getAccount(toAddress)
toAccount.balance.iadd(this._env.contract.balance)
await this._state.putAccount(toAddress, toAccount)
// Subtract from contract balance
const account = await this._state.getAccount(this._env.address)
account.balance = new BN(0)
await this._state.putAccount(this._env.address, account)
trap(ERROR.STOP)
}
/**
* Creates a new log in the current environment.
*/
log(data: Buffer, numberOfTopics: number, topics: Buffer[]): void {
if (numberOfTopics < 0 || numberOfTopics > 4) {
trap(ERROR.OUT_OF_RANGE)
}
if (topics.length !== numberOfTopics) {
trap(ERROR.INTERNAL_ERROR)
}
const log: Log = [this._env.address.buf, topics, data]
this._result.logs.push(log)
}
/**
* Sends a message with arbitrary data to a given address path.
*/
async call(gasLimit: BN, address: Address, value: BN, data: Buffer): Promise<BN> {
const msg = new Message({
caller: this._env.address,
gasLimit,
to: address,
value,
data,
isStatic: this._env.isStatic,
depth: this._env.depth + 1,
})
return this._baseCall(msg)
}
/**
* Message-call into this account with an alternative account's code.
*/
async callCode(gasLimit: BN, address: Address, value: BN, data: Buffer): Promise<BN> {
const msg = new Message({
caller: this._env.address,
gasLimit,
to: this._env.address,
codeAddress: address,
value,
data,
isStatic: this._env.isStatic,
depth: this._env.depth + 1,
})
return this._baseCall(msg)
}
/**
* Sends a message with arbitrary data to a given address path, but disallow
* state modifications. This includes log, create, selfdestruct and call with
* a non-zero value.
*/
async callStatic(gasLimit: BN, address: Address, value: BN, data: Buffer): Promise<BN> {
const msg = new Message({
caller: this._env.address,
gasLimit,
to: address,
value,
data,
isStatic: true,
depth: this._env.depth + 1,
})
return this._baseCall(msg)
}
/**
* Message-call into this account with an alternative account’s code, but
* persisting the current values for sender and value.
*/
async callDelegate(gasLimit: BN, address: Address, value: BN, data: Buffer): Promise<BN> {
const msg = new Message({
caller: this._env.caller,
gasLimit,
to: this._env.address,
codeAddress: address,
value,
data,
isStatic: this._env.isStatic,
delegatecall: true,
depth: this._env.depth + 1,
})
return this._baseCall(msg)
}
async _baseCall(msg: Message): Promise<BN> {
const selfdestruct = { ...this._result.selfdestruct }
msg.selfdestruct = selfdestruct
// empty the return data buffer
this._lastReturned = Buffer.alloc(0)
// Check if account has enough ether and max depth not exceeded
if (
this._env.depth >= this._common.param('vm', 'stackLimit') ||
(msg.delegatecall !== true && this._env.contract.balance.lt(msg.value))
) {
return new BN(0)
}
const results = await this._evm.executeMessage(msg)
if (results.execResult.logs) {
this._result.logs = this._result.logs.concat(results.execResult.logs)
}
// this should always be safe
this.useGas(results.gasUsed, 'CALL, STATICCALL, DELEGATECALL, CALLCODE')
// Set return value
if (
results.execResult.returnValue &&
(!results.execResult.exceptionError ||
results.execResult.exceptionError.error === ERROR.REVERT)
) {
this._lastReturned = results.execResult.returnValue
}
if (!results.execResult.exceptionError) {
Object.assign(this._result.selfdestruct, selfdestruct)
// update stateRoot on current contract
const account = await this._state.getAccount(this._env.address)
this._env.contract = account
}
return this._getReturnCode(results)
}
/**
* Creates a new contract with a given value.
*/
async create(gasLimit: BN, value: BN, data: Buffer, salt: Buffer | null = null): Promise<BN> {
const selfdestruct = { ...this._result.selfdestruct }
const msg = new Message({
caller: this._env.address,
gasLimit,
value,
data,
salt,
depth: this._env.depth + 1,
selfdestruct,
})
// empty the return data buffer
this._lastReturned = Buffer.alloc(0)
// Check if account has enough ether and max depth not exceeded
if (
this._env.depth >= this._common.param('vm', 'stackLimit') ||
(msg.delegatecall !== true && this._env.contract.balance.lt(msg.value))
) {
return new BN(0)
}
// EIP-2681 check
if (this._env.contract.nonce.gte(MAX_UINT64)) {
return new BN(0)
}
this._env.contract.nonce.iaddn(1)
await this._state.putAccount(this._env.address, this._env.contract)
if (this._common.isActivatedEIP(3860)) {
if (msg.data.length > this._common.param('vm', 'maxInitCodeSize')) {
return new BN(0)
}
}
const results = await this._evm.executeMessage(msg)
if (results.execResult.logs) {
this._result.logs = this._result.logs.concat(results.execResult.logs)
}
// this should always be safe
this.useGas(results.gasUsed, 'CREATE')
// Set return buffer in case revert happened
if (
results.execResult.exceptionError &&
results.execResult.exceptionError.error === ERROR.REVERT
) {
this._lastReturned = results.execResult.returnValue
}
if (
!results.execResult.exceptionError ||
results.execResult.exceptionError.error === ERROR.CODESTORE_OUT_OF_GAS
) {
Object.assign(this._result.selfdestruct, selfdestruct)
// update stateRoot on current contract
const account = await this._state.getAccount(this._env.address)
this._env.contract = account
if (results.createdAddress) {
// push the created address to the stack
return new BN(results.createdAddress.buf)
}
}
return this._getReturnCode(results)
}
/**
* Creates a new contract with a given value. Generates
* a deterministic address via CREATE2 rules.
*/
async create2(gasLimit: BN, value: BN, data: Buffer, salt: Buffer): Promise<BN> {
return this.create(gasLimit, value, data, salt)
}
/**
* Returns true if account is empty or non-existent (according to EIP-161).
* @param address - Address of account
*/
async isAccountEmpty(address: Address): Promise<boolean> {
return this._state.accountIsEmpty(address)
}
/**
* Returns true if account exists in the state trie (it can be empty). Returns false if the account is `null`.
* @param address - Address of account
*/
async accountExists(address: Address): Promise<boolean> {
return this._state.accountExists(address)
}
private _getReturnCode(results: EVMResult) {
// This preserves the previous logic, but seems to contradict the EEI spec
// https://github.com/ewasm/design/blob/38eeded28765f3e193e12881ea72a6ab807a3371/eth_interface.md
if (results.execResult.exceptionError) {
return new BN(0)
} else {
return new BN(1)
}
}
}