-
Notifications
You must be signed in to change notification settings - Fork 803
/
Copy pathinterpreter.ts
1335 lines (1196 loc) · 40.2 KB
/
interpreter.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ConsensusAlgorithm } from '@ethereumjs/common'
import {
Account,
BIGINT_0,
BIGINT_1,
BIGINT_2,
EthereumJSErrorWithoutCode,
MAX_UINT64,
bigIntToBytes,
bigIntToHex,
bytesToBigInt,
bytesToHex,
equalsBytes,
setLengthLeft,
setLengthRight,
} from '@ethereumjs/util'
import debugDefault from 'debug'
import { FORMAT, MAGIC, VERSION } from './eof/constants.ts'
import { EOFContainerMode, validateEOF } from './eof/container.ts'
import { setupEOF } from './eof/setup.ts'
import { ContainerSectionType } from './eof/verify.ts'
import { ERROR, EvmError } from './exceptions.ts'
import { type EVMPerformanceLogger, type Timer } from './logger.ts'
import { Memory } from './memory.ts'
import { Message } from './message.ts'
import { trap } from './opcodes/index.ts'
import { Stack } from './stack.ts'
import type {
BinaryTreeAccessWitnessInterface,
Common,
StateManagerInterface,
VerkleAccessWitnessInterface,
} from '@ethereumjs/common'
import type { Address, PrefixedHexString } from '@ethereumjs/util'
import { stackDelta } from './eof/stackDelta.ts'
import type { EVM } from './evm.ts'
import type { Journal } from './journal.ts'
import type { AsyncOpHandler, Opcode, OpcodeMapEntry } from './opcodes/index.ts'
import type {
Block,
EOFEnv,
EVMMockBlockchainInterface,
EVMProfilerOpts,
EVMResult,
Log,
} from './types.ts'
const debugGas = debugDefault('evm:gas')
export interface InterpreterOpts {
pc?: number
}
/**
* Immediate (unprocessed) result of running an EVM bytecode.
*/
export interface RunResult {
logs: Log[]
returnValue?: Uint8Array
/**
* A set of accounts to selfdestruct
*/
selfdestruct: Set<PrefixedHexString>
/**
* A map which tracks which addresses were created (used in EIP 6780)
*/
createdAddresses?: Set<PrefixedHexString>
}
export interface Env {
address: Address
caller: Address
callData: Uint8Array
callValue: bigint
code: Uint8Array
isStatic: boolean
isCreate: boolean
depth: number
gasPrice: bigint
origin: Address
block: Block
contract: Account
codeAddress: Address /* Different than address for DELEGATECALL and CALLCODE */
gasRefund: bigint /* Current value (at begin of the frame) of the gas refund */
eof?: EOFEnv /* Optional EOF environment in case of EOF execution */
blobVersionedHashes: PrefixedHexString[] /** Versioned hashes for blob transactions */
createdAddresses?: Set<string>
accessWitness?: VerkleAccessWitnessInterface | BinaryTreeAccessWitnessInterface
chargeCodeAccesses?: boolean
}
export interface RunState {
programCounter: number
opCode: number
memory: Memory
memoryWordCount: bigint
highestMemCost: bigint
stack: Stack
code: Uint8Array
shouldDoJumpAnalysis: boolean
validJumps: Uint8Array // array of values where validJumps[index] has value 0 (default), 1 (jumpdest), 2 (beginsub)
cachedPushes: { [pc: number]: bigint }
stateManager: StateManagerInterface
blockchain: EVMMockBlockchainInterface
env: Env
messageGasLimit?: bigint // Cache value from `gas.ts` to save gas limit for a message call
interpreter: Interpreter
gasRefund: bigint // Tracks the current refund
gasLeft: bigint // Current gas left
returnBytes: Uint8Array /* Current bytes in the return Uint8Array. Cleared each time a CALL/CREATE is made in the current frame. */
accessedStorage: Map<PrefixedHexString, PrefixedHexString>
}
export interface InterpreterResult {
runState: RunState
exceptionError?: EvmError
}
export interface InterpreterStep {
gasLeft: bigint
gasRefund: bigint
stateManager: StateManagerInterface
stack: bigint[]
pc: number
depth: number
opcode: {
name: string
fee: number
dynamicFee?: bigint
isAsync: boolean
code: number // The hexadecimal representation of the opcode (e.g. 0x60 for PUSH1)
}
account: Account
address: Address
memory: Uint8Array
memoryWordCount: bigint
codeAddress: Address
eofSection?: number // Current EOF section being executed
immediate?: Uint8Array // Immediate argument of the opcode
eofFunctionDepth?: number // Depth of CALLF return stack
error?: Uint8Array // Error bytes returned if revert occurs
storage?: [PrefixedHexString, PrefixedHexString][]
}
/**
* Parses and executes EVM bytecode.
*/
export class Interpreter {
protected _vm: any
protected _runState: RunState
protected _stateManager: StateManagerInterface
protected common: Common
public _evm: EVM
public journal: Journal
_env: Env
// Keep track of this Interpreter run result
// TODO move into Env?
_result: RunResult
// Opcode debuggers (e.g. { 'push': [debug Object], 'sstore': [debug Object], ...})
private opDebuggers: { [key: string]: (debug: string) => void } = {}
private profilerOpts?: EVMProfilerOpts
private performanceLogger: EVMPerformanceLogger
// TODO remove gasLeft as constructor argument
constructor(
evm: EVM,
stateManager: StateManagerInterface,
blockchain: EVMMockBlockchainInterface,
env: Env,
gasLeft: bigint,
journal: Journal,
performanceLogs: EVMPerformanceLogger,
profilerOpts?: EVMProfilerOpts,
) {
this._evm = evm
this._stateManager = stateManager
this.common = this._evm.common
if (
this.common.consensusType() === 'poa' &&
this._evm['_optsCached'].cliqueSigner === undefined
)
throw EthereumJSErrorWithoutCode(
'Must include cliqueSigner function if clique/poa is being used for consensus type',
)
this._runState = {
programCounter: 0,
opCode: 0xfe, // INVALID opcode
memory: new Memory(),
memoryWordCount: BIGINT_0,
highestMemCost: BIGINT_0,
stack: new Stack(),
code: new Uint8Array(0),
validJumps: Uint8Array.from([]),
cachedPushes: {},
stateManager: this._stateManager,
blockchain,
env,
shouldDoJumpAnalysis: true,
interpreter: this,
gasRefund: env.gasRefund,
gasLeft,
returnBytes: new Uint8Array(0),
accessedStorage: new Map(), // Maps accessed storage keys to their values (i.e. SSTOREd and SLOADed values)
}
this.journal = journal
this._env = env
this._result = {
logs: [],
returnValue: undefined,
selfdestruct: new Set(),
}
this.profilerOpts = profilerOpts
this.performanceLogger = performanceLogs
}
async run(code: Uint8Array, opts: InterpreterOpts = {}): Promise<InterpreterResult> {
if (!this.common.isActivatedEIP(3540) || code[0] !== FORMAT) {
// EIP-3540 isn't active and first byte is not 0xEF - treat as legacy bytecode
this._runState.code = code
} else if (this.common.isActivatedEIP(3540)) {
if (code[1] !== MAGIC) {
// Bytecode contains invalid EOF magic byte
return {
runState: this._runState,
exceptionError: new EvmError(ERROR.INVALID_BYTECODE_RESULT),
}
}
if (code[2] !== VERSION) {
// Bytecode contains invalid EOF version number
return {
runState: this._runState,
exceptionError: new EvmError(ERROR.INVALID_EOF_FORMAT),
}
}
this._runState.code = code
const isTxCreate = this._env.isCreate && this._env.depth === 0
const eofMode = isTxCreate ? EOFContainerMode.TxInitmode : EOFContainerMode.Default
try {
setupEOF(this._runState, eofMode)
} catch {
return {
runState: this._runState,
exceptionError: new EvmError(ERROR.INVALID_EOF_FORMAT), // TODO: verify if all gas should be consumed
}
}
if (isTxCreate) {
// Tx tries to deploy container
try {
validateEOF(
this._runState.code,
this._evm,
ContainerSectionType.InitCode,
EOFContainerMode.TxInitmode,
)
} catch {
// Trying to deploy an invalid EOF container
return {
runState: this._runState,
exceptionError: new EvmError(ERROR.INVALID_EOF_FORMAT), // TODO: verify if all gas should be consumed
}
}
}
}
this._runState.programCounter = opts.pc ?? this._runState.programCounter
// Check that the programCounter is in range
const pc = this._runState.programCounter
if (pc !== 0 && (pc < 0 || pc >= this._runState.code.length)) {
throw EthereumJSErrorWithoutCode('Internal error: program counter not in range')
}
let err
let cachedOpcodes: OpcodeMapEntry[]
let doJumpAnalysis = true
let timer: Timer | undefined
let overheadTimer: Timer | undefined
if (this.profilerOpts?.enabled === true && this.performanceLogger.hasTimer()) {
timer = this.performanceLogger.pauseTimer()
overheadTimer = this.performanceLogger.startTimer('Overhead')
}
// Iterate through the given ops until something breaks or we hit STOP
while (this._runState.programCounter < this._runState.code.length) {
const programCounter = this._runState.programCounter
let opCode: number
let opCodeObj: OpcodeMapEntry | undefined
if (doJumpAnalysis) {
opCode = this._runState.code[programCounter]
// Only run the jump destination analysis if `code` actually contains a JUMP/JUMPI/JUMPSUB opcode
if (opCode === 0x56 || opCode === 0x57 || opCode === 0x5e) {
const { jumps, pushes, opcodesCached } = this._getValidJumpDestinations(
this._runState.code,
)
this._runState.validJumps = jumps
this._runState.cachedPushes = pushes
this._runState.shouldDoJumpAnalysis = false
cachedOpcodes = opcodesCached
doJumpAnalysis = false
}
} else {
opCodeObj = cachedOpcodes![programCounter]
opCode = opCodeObj.opcodeInfo.code
}
// if its an invalid opcode with verkle activated, then check if its because of a missing code
// chunk in the witness, and throw appropriate error to distinguish from an actual invalid opcode
if (
opCode === 0xfe &&
(this.common.isActivatedEIP(6800) || this.common.isActivatedEIP(7864)) &&
// is this a code loaded from state using witnesses
this._runState.env.chargeCodeAccesses === true
) {
const contract = this._runState.interpreter.getAddress()
if (
!(await this._runState.stateManager.checkChunkWitnessPresent!(contract, programCounter))
) {
throw Error(`Invalid witness with missing codeChunk for pc=${programCounter}`)
}
}
this._runState.opCode = opCode
try {
if (overheadTimer !== undefined) {
this.performanceLogger.pauseTimer()
}
await this.runStep(opCodeObj)
if (overheadTimer !== undefined) {
this.performanceLogger.unpauseTimer(overheadTimer)
}
} catch (e: any) {
// Revert access witness changes if we revert - per EIP-4762
this._runState.env.accessWitness?.revert()
if (overheadTimer !== undefined) {
this.performanceLogger.unpauseTimer(overheadTimer)
}
// re-throw on non-VM errors
if (!('errorType' in e && e.errorType === 'EvmError')) {
throw e
}
// STOP is not an exception
if (e.error !== ERROR.STOP) {
err = e
}
break
}
}
if (timer !== undefined) {
this.performanceLogger.stopTimer(overheadTimer!, 0)
this.performanceLogger.unpauseTimer(timer)
}
return {
runState: this._runState,
exceptionError: err,
}
}
/**
* Executes the opcode to which the program counter is pointing,
* reducing its base gas cost, and increments the program counter.
*/
async runStep(opcodeObj?: OpcodeMapEntry): Promise<void> {
const opEntry = opcodeObj ?? this.lookupOpInfo(this._runState.opCode)
const opInfo = opEntry.opcodeInfo
let timer: Timer
if (this.profilerOpts?.enabled === true) {
timer = this.performanceLogger.startTimer(opInfo.name)
}
let gas = opInfo.feeBigInt
// Cache pre-gas memory size if doing tracing (EIP-7756)
const memorySizeCache = this._runState.memoryWordCount
try {
if (opInfo.dynamicGas) {
// This function updates the gas in-place.
// It needs the base fee, for correct gas limit calculation for the CALL opcodes
gas = await opEntry.gasHandler(this._runState, gas, this.common)
}
if (this._evm.events.listenerCount('step') > 0 || this._evm.DEBUG) {
// Only run this stepHook function if there is an event listener (e.g. test runner)
// or if the vm is running in debug mode (to display opcode debug logs)
await this._runStepHook(gas, this.getGasLeft(), memorySizeCache)
}
if (
(this.common.isActivatedEIP(6800) || this.common.isActivatedEIP(7864)) &&
this._env.chargeCodeAccesses === true
) {
const contract = this._runState.interpreter.getAddress()
const statelessGas = this._runState.env.accessWitness!.readAccountCodeChunks(
contract,
this._runState.programCounter,
this._runState.programCounter,
)
gas += statelessGas
debugGas(`codechunk accessed statelessGas=${statelessGas} (-> ${gas})`)
}
// Check for invalid opcode
if (opInfo.isInvalid) {
throw new EvmError(ERROR.INVALID_OPCODE)
}
// Reduce opcode's base fee
this.useGas(gas, opInfo)
// Advance program counter
this._runState.programCounter++
// Execute opcode handler
const opFn = opEntry.opHandler
if (opInfo.isAsync) {
await (opFn as AsyncOpHandler).apply(null, [this._runState, this.common])
} else {
opFn.apply(null, [this._runState, this.common])
}
this._runState.env.accessWitness?.commit()
} finally {
if (this.profilerOpts?.enabled === true) {
this.performanceLogger.stopTimer(
timer!,
Number(gas),
'opcodes',
opInfo.fee,
Number(gas) - opInfo.fee,
)
}
}
}
/**
* Get info for an opcode from EVM's list of opcodes.
*/
lookupOpInfo(op: number): OpcodeMapEntry {
return this._evm['_opcodeMap'][op]
}
async _runStepHook(dynamicFee: bigint, gasLeft: bigint, memorySize: bigint): Promise<void> {
const opcodeInfo = this.lookupOpInfo(this._runState.opCode).opcodeInfo
const section = this._env.eof?.container.header.getSectionFromProgramCounter(
this._runState.programCounter,
)
let error = undefined
let immediate = undefined
if (opcodeInfo.code === 0xfd) {
// If opcode is REVERT, read error data and return in trace
const [offset, length] = this._runState.stack.peek(2)
error = new Uint8Array(0)
if (length !== BIGINT_0) {
error = this._runState.memory.read(Number(offset), Number(length))
}
}
// Add immediate if present (i.e. bytecode parameter for a preceding opcode like (RJUMP 01 - jumps to PC 1))
if (stackDelta[opcodeInfo.code].intermediates > 0) {
immediate = this._runState.code.slice(
this._runState.programCounter,
this._runState.programCounter + stackDelta[opcodeInfo.code].intermediates,
)
}
if (opcodeInfo.name === 'SLOAD') {
// Store SLOADed values for recording in trace
const key = this._runState.stack.peek(1)
const value = await this.storageLoad(setLengthLeft(bigIntToBytes(key[0]), 32))
this._runState.accessedStorage.set(`0x${key[0].toString(16)}`, bytesToHex(value))
}
if (opcodeInfo.name === 'SSTORE') {
// Store SSTOREed values for recording in trace
const [key, value] = this._runState.stack.peek(2)
this._runState.accessedStorage.set(`0x${key.toString(16)}`, `0x${value.toString(16)}`)
}
// Create event object for step
const eventObj: InterpreterStep = {
pc: this._runState.programCounter,
gasLeft,
gasRefund: this._runState.gasRefund,
opcode: {
name: opcodeInfo.fullName,
fee: opcodeInfo.fee,
dynamicFee,
isAsync: opcodeInfo.isAsync,
code: opcodeInfo.code,
},
stack: this._runState.stack.getStack(),
depth: this._env.depth,
address: this._env.address,
account: this._env.contract,
memory: this._runState.memory._store.subarray(0, Number(memorySize) * 32),
memoryWordCount: memorySize,
codeAddress: this._env.codeAddress,
stateManager: this._runState.stateManager,
eofSection: section,
immediate,
error,
eofFunctionDepth:
this._env.eof !== undefined ? this._env.eof?.eofRunState.returnStack.length + 1 : undefined,
storage: Array.from(this._runState.accessedStorage.entries()),
}
if (this._evm.DEBUG) {
// Create opTrace for debug functionality
let hexStack = []
hexStack = eventObj.stack.map((item: any) => {
return bigIntToHex(BigInt(item))
})
const name = eventObj.opcode.name
const opTrace = {
pc: eventObj.pc,
op: name,
gas: bigIntToHex(eventObj.gasLeft),
gasCost: bigIntToHex(dynamicFee),
stack: hexStack,
depth: eventObj.depth,
}
if (!(name in this.opDebuggers)) {
this.opDebuggers[name] = debugDefault(`evm:ops:${name}`)
}
this.opDebuggers[name](JSON.stringify(opTrace))
}
/**
* The `step` event for trace output
*
* @event Event: step
* @type {Object}
* @property {Number} pc representing the program counter
* @property {Object} opcode the next opcode to be ran
* @property {string} opcode.name
* @property {fee} opcode.number Base fee of the opcode
* @property {dynamicFee} opcode.dynamicFee Dynamic opcode fee
* @property {boolean} opcode.isAsync opcode is async
* @property {number} opcode.code opcode code
* @property {BigInt} gasLeft amount of gasLeft
* @property {BigInt} gasRefund gas refund
* @property {StateManager} stateManager a {@link StateManager} instance
* @property {Array} stack an `Array` of `Uint8Arrays` containing the stack
* @property {Array} returnStack the return stack
* @property {Account} account the Account which owns the code running
* @property {Address} address the address of the `account`
* @property {Number} depth the current number of calls deep the contract is
* @property {Uint8Array} memory the memory of the EVM as a `Uint8Array`
* @property {BigInt} memoryWordCount current size of memory in words
* @property {Address} codeAddress the address of the code which is currently being ran (this differs from `address` in a `DELEGATECALL` and `CALLCODE` call)
* @property {number} eofSection the current EOF code section referenced by the PC
* @property {Uint8Array} immediate the immediate argument of the opcode
* @property {Uint8Array} error the error data of the opcode (only present for REVERT)
* @property {number} eofFunctionDepth the depth of the function call (only present for EOF)
* @property {Array} storage an array of tuples, where each tuple contains a storage key and value
*/
await this._evm['_emit']('step', eventObj)
}
// Returns all valid jump and jumpsub destinations.
_getValidJumpDestinations(code: Uint8Array) {
const jumps = new Uint8Array(code.length)
const pushes: { [pc: number]: bigint } = {}
const opcodesCached = Array(code.length)
for (let i = 0; i < code.length; i++) {
const opcode = code[i]
opcodesCached[i] = this.lookupOpInfo(opcode)
// skip over PUSH0-32 since no jump destinations in the middle of a push block
if (opcode <= 0x7f) {
if (opcode >= 0x60) {
const bytesToPush = opcode - 0x5f
let pushBytes = code.subarray(i + 1, i + opcode - 0x5e)
if (pushBytes.length < bytesToPush) {
pushBytes = setLengthRight(pushBytes, bytesToPush)
}
const push = bytesToBigInt(pushBytes)
pushes[i + 1] = push
i += bytesToPush
} else if (opcode === 0x5b) {
// Define a JUMPDEST as a 1 in the valid jumps array
jumps[i] = 1
}
}
}
return { jumps, pushes, opcodesCached }
}
/**
* 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: bigint, context?: string | Opcode): void {
this._runState.gasLeft -= amount
if (this._evm.DEBUG) {
let tempString = ''
if (typeof context === 'string') {
tempString = context + ': '
} else if (context !== undefined) {
tempString = `${context.name} fee: `
}
debugGas(`${tempString}used ${amount} gas (-> ${this._runState.gasLeft})`)
}
if (this._runState.gasLeft < BIGINT_0) {
this._runState.gasLeft = BIGINT_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: bigint, context?: string): void {
if (this._evm.DEBUG) {
debugGas(
`${typeof context === 'string' ? context + ': ' : ''}refund ${amount} gas (-> ${
this._runState.gasRefund
})`,
)
}
this._runState.gasRefund += 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: bigint, context?: string): void {
if (this._evm.DEBUG) {
debugGas(
`${typeof context === 'string' ? context + ': ' : ''}sub gas refund ${amount} (-> ${
this._runState.gasRefund
})`,
)
}
this._runState.gasRefund -= amount
if (this._runState.gasRefund < BIGINT_0) {
this._runState.gasRefund = BIGINT_0
trap(ERROR.REFUND_EXHAUSTED)
}
}
/**
* Increments the internal gasLeft counter. Used for adding callStipend.
* @param amount - Amount to add
*/
addStipend(amount: bigint): void {
if (this._evm.DEBUG) {
debugGas(`add stipend ${amount} (-> ${this._runState.gasLeft})`)
}
this._runState.gasLeft += amount
}
/**
* Returns balance of the given account.
* @param address - Address of account
*/
async getExternalBalance(address: Address): Promise<bigint> {
// shortcut if current account
if (address.equals(this._env.address)) {
return this._env.contract.balance
}
let account = await this._stateManager.getAccount(address)
if (!account) {
account = new Account()
}
return account.balance
}
/**
* Store 256-bit a value in memory to persistent storage.
*/
async storageStore(key: Uint8Array, value: Uint8Array): Promise<void> {
await this._stateManager.putStorage(this._env.address, key, value)
const account = await this._stateManager.getAccount(this._env.address)
if (!account) {
throw EthereumJSErrorWithoutCode('could not read account while persisting memory')
}
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: Uint8Array, original = false): Promise<Uint8Array> {
if (original) {
return this._stateManager.originalStorageCache.get(this._env.address, key)
} else {
return this._stateManager.getStorage(this._env.address, key)
}
}
/**
* Store 256-bit a value in memory to transient storage.
* @param address Address to use
* @param key Storage key
* @param value Storage value
*/
transientStorageStore(key: Uint8Array, value: Uint8Array): void {
return this._evm.transientStorage.put(this._env.address, key, value)
}
/**
* Loads a 256-bit value to memory from transient storage.
* @param address Address to use
* @param key Storage key
*/
transientStorageLoad(key: Uint8Array): Uint8Array {
return this._evm.transientStorage.get(this._env.address, key)
}
/**
* Set the returning output data for the execution.
* @param returnData - Output data to return
*/
finish(returnData: Uint8Array): 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: Uint8Array): void {
this._result.returnValue = returnData
trap(ERROR.REVERT)
}
/**
* Returns address of currently executing account.
*/
getAddress(): Address {
return this._env.address
}
/**
* Returns balance of self.
*/
getSelfBalance(): bigint {
return this._env.contract.balance
}
/**
* Returns the deposited value by the instruction/transaction
* responsible for this execution.
*/
getCallValue(): bigint {
return this._env.callValue
}
/**
* Returns input data in current environment. This pertains to the input
* data passed with the message call instruction or transaction.
*/
getCallData(): Uint8Array {
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(): bigint {
return BigInt(this._env.callData.length)
}
/**
* Returns caller address. This is the address of the account
* that is directly responsible for this execution.
*/
getCaller(): bigint {
return bytesToBigInt(this._env.caller.bytes)
}
/**
* Returns the size of code running in current environment.
*/
getCodeSize(): bigint {
return BigInt(this._env.code.length)
}
/**
* Returns the code running in current environment.
*/
getCode(): Uint8Array {
return this._env.code
}
/**
* Returns the current gasCounter.
*/
getGasLeft(): bigint {
return this._runState.gasLeft
}
/**
* 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(): bigint {
return BigInt(this._runState.returnBytes.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(): Uint8Array {
return this._runState.returnBytes
}
/**
* Returns true if the current call must be executed statically.
*/
isStatic(): boolean {
return this._env.isStatic
}
/**
* Returns price of gas in current environment.
*/
getTxGasPrice(): bigint {
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(): bigint {
return bytesToBigInt(this._env.origin.bytes)
}
/**
* Returns the block's number.
*/
getBlockNumber(): bigint {
return this._env.block.header.number
}
/**
* Returns the block's beneficiary address.
*/
getBlockCoinbase(): bigint {
let coinbase: Address
if (this.common.consensusAlgorithm() === ConsensusAlgorithm.Clique) {
coinbase = this._evm['_optsCached'].cliqueSigner!(this._env.block.header)
} else {
coinbase = this._env.block.header.coinbase
}
return bytesToBigInt(coinbase.toBytes())
}
/**
* Returns the block's timestamp.
*/
getBlockTimestamp(): bigint {
return this._env.block.header.timestamp
}
/**
* Returns the block's difficulty.
*/
getBlockDifficulty(): bigint {
return this._env.block.header.difficulty
}
/**
* Returns the block's prevRandao field.
*/
getBlockPrevRandao(): bigint {
return bytesToBigInt(this._env.block.header.prevRandao)
}
/**
* Returns the block's gas limit.
*/
getBlockGasLimit(): bigint {
return this._env.block.header.gasLimit
}
/**
* Returns the Base Fee of the block as proposed in [EIP-3198](https://eips.ethereum.org/EIPS/eip-3198)
*/
getBlockBaseFee(): bigint {
const baseFee = this._env.block.header.baseFeePerGas
if (baseFee === undefined) {
// Sanity check
throw EthereumJSErrorWithoutCode('Block has no Base Fee')
}
return baseFee
}
/**
* Returns the Blob Base Fee of the block as proposed in [EIP-7516](https://eips.ethereum.org/EIPS/eip-7516)
*/
getBlobBaseFee(): bigint {
const blobBaseFee = this._env.block.header.getBlobGasPrice()
if (blobBaseFee === undefined) {
// Sanity check
throw EthereumJSErrorWithoutCode('Block has no Blob Base Fee')
}
return blobBaseFee
}
/**
* Returns the chain ID for current chain. Introduced for the
* CHAINID opcode proposed in [EIP-1344](https://eips.ethereum.org/EIPS/eip-1344).
*/
getChainId(): bigint {
return this.common.chainId()
}
/**
* Sends a message with arbitrary data to a given address path.
*/
async call(gasLimit: bigint, address: Address, value: bigint, data: Uint8Array): Promise<bigint> {
const msg = new Message({
caller: this._env.address,
gasLimit,
to: address,
value,
data,
isStatic: this._env.isStatic,
depth: this._env.depth + 1,
blobVersionedHashes: this._env.blobVersionedHashes,
accessWitness: this._env.accessWitness,
})
return this._baseCall(msg)
}
/**
* Message-call into this account with an alternative account's code.
*/
async callCode(
gasLimit: bigint,
address: Address,
value: bigint,
data: Uint8Array,
): Promise<bigint> {
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,
blobVersionedHashes: this._env.blobVersionedHashes,
accessWitness: this._env.accessWitness,
})
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: bigint,
address: Address,
value: bigint,
data: Uint8Array,