-
Notifications
You must be signed in to change notification settings - Fork 33
/
standard_cheat_code_contract.go
511 lines (448 loc) · 17.8 KB
/
standard_cheat_code_contract.go
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
package chain
import (
"crypto/ecdsa"
"encoding/hex"
"fmt"
"github.com/crytic/medusa/utils"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
"os/exec"
"strconv"
"strings"
)
// StandardCheatcodeContractAddress is the address for the standard cheatcode contract
var StandardCheatcodeContractAddress = common.HexToAddress("0x7109709ECfa91a80626fF3989D68f67F5b1DD12D")
// MaxUint64 holds the max value an uint64 can take
var _, MaxUint64 = utils.GetIntegerConstraints(false, 64)
// getStandardCheatCodeContract obtains a CheatCodeContract which implements common cheat codes.
// Returns the precompiled contract, or an error if one occurs.
func getStandardCheatCodeContract(tracer *cheatCodeTracer) (*CheatCodeContract, error) {
// Create a new precompile to add methods to.
contract := newCheatCodeContract(tracer, StandardCheatcodeContractAddress, "StdCheats")
// Define some basic ABI argument types
typeAddress, err := abi.NewType("address", "", nil)
if err != nil {
return nil, err
}
typeBytes, err := abi.NewType("bytes", "", nil)
if err != nil {
return nil, err
}
typeBytes32, err := abi.NewType("bytes32", "", nil)
if err != nil {
return nil, err
}
typeUint8, err := abi.NewType("uint8", "", nil)
if err != nil {
return nil, err
}
typeUint64, err := abi.NewType("uint64", "", nil)
if err != nil {
return nil, err
}
typeUint256, err := abi.NewType("uint256", "", nil)
if err != nil {
return nil, err
}
typeInt256, err := abi.NewType("int256", "", nil)
if err != nil {
return nil, err
}
typeStringSlice, err := abi.NewType("string[]", "", nil)
if err != nil {
return nil, err
}
typeString, err := abi.NewType("string", "", nil)
if err != nil {
return nil, err
}
typeBool, err := abi.NewType("bool", "", nil)
if err != nil {
return nil, err
}
// Warp: Sets VM timestamp
contract.addMethod(
"warp", abi.Arguments{{Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes until the transaction exits.
originalTime := tracer.evm.Context.Time
// Retrieve new timestamp and make sure it is LEQ max value of an uint64
newTime := inputs[0].(*big.Int)
if newTime.Cmp(MaxUint64) > 0 {
return nil, cheatCodeRevertData([]byte("warp: timestamp exceeds max value of type(uint64).max"))
}
// Set the time
tracer.evm.Context.Time = newTime.Uint64()
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
// Reset the time
tracer.evm.Context.Time = originalTime
})
return nil, nil
},
)
// Roll: Sets VM block number
contract.addMethod(
"roll", abi.Arguments{{Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes until the transaction exits.
original := new(big.Int).Set(tracer.evm.Context.BlockNumber)
tracer.evm.Context.BlockNumber.Set(inputs[0].(*big.Int))
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
tracer.evm.Context.BlockNumber.Set(original)
})
return nil, nil
},
)
// Fee: Update base fee
contract.addMethod(
"fee", abi.Arguments{{Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes until the transaction exits.
original := new(big.Int).Set(tracer.evm.Context.BaseFee)
tracer.evm.Context.BaseFee.Set(inputs[0].(*big.Int))
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
tracer.evm.Context.BaseFee.Set(original)
})
return nil, nil
},
)
// Difficulty: Sets VM block number
contract.addMethod(
"difficulty", abi.Arguments{{Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes until the transaction exits.
// Obtain our spoofed difficulty
spoofedDifficulty := inputs[0].(*big.Int)
spoofedDifficultyHash := common.BigToHash(spoofedDifficulty)
// Change difficulty in block context.
originalDifficulty := new(big.Int).Set(tracer.evm.Context.Difficulty)
tracer.evm.Context.Difficulty.Set(spoofedDifficulty)
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
tracer.evm.Context.Difficulty.Set(originalDifficulty)
})
// In newer evm versions, block.difficulty uses opRandom instead of opDifficulty.
// TODO: Check chain config here to see if the EVM version is 'Paris' or the consensus upgrade occurred.
originalRandom := tracer.evm.Context.Random
tracer.evm.Context.Random = &spoofedDifficultyHash
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
tracer.evm.Context.Random = originalRandom
})
return nil, nil
},
)
// ChainId: Sets VM chain ID
contract.addMethod(
"chainId", abi.Arguments{{Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes unless this code path reverts or the whole transaction is reverted in the chain.
chainConfig := tracer.evm.ChainConfig()
original := chainConfig.ChainID
chainConfig.ChainID = inputs[0].(*big.Int)
tracer.CurrentCallFrame().onChainRevertRestoreHooks.Push(func() {
chainConfig.ChainID = original
})
return nil, nil
},
)
// Store: Sets a storage slot value in a given account.
contract.addMethod(
"store", abi.Arguments{{Type: typeAddress}, {Type: typeBytes32}, {Type: typeBytes32}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
slot := inputs[1].([32]byte)
value := inputs[2].([32]byte)
tracer.evm.StateDB.SetState(account, slot, value)
return nil, nil
},
)
// Load: Loads a storage slot value from a given account.
contract.addMethod(
"load", abi.Arguments{{Type: typeAddress}, {Type: typeBytes32}}, abi.Arguments{{Type: typeBytes32}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
slot := inputs[1].([32]byte)
value := tracer.evm.StateDB.GetState(account, slot)
return []any{value}, nil
},
)
// Etch: Sets the code for a given account.
contract.addMethod(
"etch", abi.Arguments{{Type: typeAddress}, {Type: typeBytes}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
code := inputs[1].([]byte)
tracer.evm.StateDB.SetCode(account, code)
return nil, nil
},
)
// Deal: Sets the balance for a given account.
contract.addMethod(
"deal", abi.Arguments{{Type: typeAddress}, {Type: typeUint256}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
newBalance := inputs[1].(*big.Int)
originalBalance := tracer.evm.StateDB.GetBalance(account)
diff := new(big.Int).Sub(newBalance, originalBalance)
tracer.evm.StateDB.AddBalance(account, diff)
return nil, nil
},
)
// GetNonce: Gets the nonce for a given account.
contract.addMethod(
"getNonce", abi.Arguments{{Type: typeAddress}}, abi.Arguments{{Type: typeUint64}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
nonce := tracer.evm.StateDB.GetNonce(account)
return []any{nonce}, nil
},
)
// SetNonce: Sets the nonce for a given account.
contract.addMethod(
"setNonce", abi.Arguments{{Type: typeAddress}, {Type: typeUint64}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
account := inputs[0].(common.Address)
nonce := inputs[1].(uint64)
tracer.evm.StateDB.SetNonce(account, nonce)
return nil, nil
},
)
// Coinbase: Sets the block coinbase.
contract.addMethod(
"coinbase", abi.Arguments{{Type: typeAddress}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Maintain our changes until the transaction exits.
original := tracer.evm.Context.Coinbase
tracer.evm.Context.Coinbase = inputs[0].(common.Address)
tracer.CurrentCallFrame().onTopFrameExitRestoreHooks.Push(func() {
tracer.evm.Context.Coinbase = original
})
return nil, nil
},
)
// Prank: Sets the msg.sender within the next EVM call scope created by the caller.
contract.addMethod(
"prank", abi.Arguments{{Type: typeAddress}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Obtain the caller frame. This is a pre-compile, so we want to add an event to the frame which called us,
// so when it enters the next frame in its scope, we trigger the prank.
cheatCodeCallerFrame := tracer.PreviousCallFrame()
cheatCodeCallerFrame.onNextFrameEnterHooks.Push(func() {
// We entered the scope we want to prank, store the original value, patch, and add a hook to restore it
// when this frame is exited.
prankCallFrame := tracer.CurrentCallFrame()
original := prankCallFrame.vmScope.Contract.CallerAddress
prankCallFrame.vmScope.Contract.CallerAddress = inputs[0].(common.Address)
prankCallFrame.onFrameExitRestoreHooks.Push(func() {
prankCallFrame.vmScope.Contract.CallerAddress = original
})
})
return nil, nil
},
)
// PrankHere: Sets the msg.sender within caller EVM scope until it is exited.
contract.addMethod(
"prankHere", abi.Arguments{{Type: typeAddress}}, abi.Arguments{},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Obtain the caller frame. This is a pre-compile, so we want to add an event to the frame which called us,
// to disable the cheat code on exit
cheatCodeCallerFrame := tracer.PreviousCallFrame()
// Store the original value, patch, and add a hook to restore it when this frame is exited.
original := cheatCodeCallerFrame.vmScope.Contract.CallerAddress
cheatCodeCallerFrame.vmScope.Contract.CallerAddress = inputs[0].(common.Address)
cheatCodeCallerFrame.onFrameExitRestoreHooks.Push(func() {
cheatCodeCallerFrame.vmScope.Contract.CallerAddress = original
})
return nil, nil
},
)
// FFI: Run arbitrary command on base OS
contract.addMethod(
"ffi", abi.Arguments{{Type: typeStringSlice}}, abi.Arguments{{Type: typeBytes}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Ensure FFI is enabled (this allows arbitrary code execution, so we expect it to be explicitly enabled).
if !tracer.chain.testChainConfig.CheatCodeConfig.EnableFFI {
// Make sure there is at least a command to run
return nil, cheatCodeRevertData([]byte("ffi is not enabled in the chain configuration"))
}
// command is cmdAndInputs[0] and args are cmdAndInputs[1:]
cmdAndInputs := inputs[0].([]string)
var command string
var args []string
if len(cmdAndInputs) < 1 {
// Make sure there is at least a command to run
return nil, cheatCodeRevertData([]byte("ffi: no command was provided"))
} else if len(cmdAndInputs) == 1 {
// It is possible there are no arguments provided
command = cmdAndInputs[0]
} else {
// Both a command and arguments have been provided
command = cmdAndInputs[0]
args = cmdAndInputs[1:]
}
// Create our command
cmd := exec.Command(command, args...)
// Execute it and grab the output
stdout, _, combined, err := utils.RunCommandWithOutputAndError(cmd)
if err != nil {
errorMsg := fmt.Sprintf("ffi: cmd failed with the following error: %v\nOutput: %v", err, string(combined))
return nil, cheatCodeRevertData([]byte(errorMsg))
}
// Attempt to hex decode the output
hexOut, err := hex.DecodeString(strings.TrimPrefix(string(stdout), "0x"))
if err != nil {
// Return the byte array as itself if hex decoding does not work
return []any{stdout}, nil
}
// Hex decoding worked, so return that
return []any{hexOut}, nil
},
)
// addr: Compute the address for a given private key
contract.addMethod("addr", abi.Arguments{{Type: typeUint256}}, abi.Arguments{{Type: typeAddress}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Get the private key object
privateKey, err := utils.GetPrivateKey(inputs[0].(*big.Int).Bytes())
if err != nil {
errorMessage := "addr: " + err.Error()
return nil, cheatCodeRevertData([]byte(errorMessage))
}
// Get ECDSA public key
publicKey := privateKey.Public().(*ecdsa.PublicKey)
// Get associated address
addr := crypto.PubkeyToAddress(*publicKey)
return []any{addr}, nil
},
)
// sign: Sign a digest given some private key
contract.addMethod("sign", abi.Arguments{{Type: typeUint256}, {Type: typeBytes32}},
abi.Arguments{{Type: typeUint8}, {Type: typeBytes32}, {Type: typeBytes32}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
// Get the private key object
privateKey, err := utils.GetPrivateKey(inputs[0].(*big.Int).Bytes())
if err != nil {
errorMessage := "sign: " + err.Error()
return nil, cheatCodeRevertData([]byte(errorMessage))
}
// Sign digest
digest := inputs[1].([32]byte)
sig, err := crypto.Sign(digest[:], privateKey)
if err != nil {
return nil, cheatCodeRevertData([]byte("sign: malformed input to signature algorithm"))
}
// `r` and `s` have to be [32]byte arrays
var r [32]byte
var s [32]byte
copy(r[:], sig[:32])
copy(s[:], sig[32:64])
// Need to add 27 to the `v` value for ecrecover to work
v := sig[64] + 27
return []any{v, r, s}, nil
},
)
// toString(address): Convert address to string
contract.addMethod("toString", abi.Arguments{{Type: typeAddress}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
addr := inputs[0].(common.Address)
return []any{addr.String()}, nil
},
)
// toString(bool): Convert bool to string
contract.addMethod("toString", abi.Arguments{{Type: typeBool}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
b := inputs[0].(bool)
return []any{strconv.FormatBool(b)}, nil
},
)
// toString(uint256): Convert uint256 to string
contract.addMethod("toString", abi.Arguments{{Type: typeUint256}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
n := inputs[0].(*big.Int)
return []any{n.String()}, nil
},
)
// toString(int256): Convert int256 to string
contract.addMethod("toString", abi.Arguments{{Type: typeInt256}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
n := inputs[0].(*big.Int)
return []any{n.String()}, nil
},
)
// toString(bytes32): Convert bytes32 to string
contract.addMethod("toString", abi.Arguments{{Type: typeBytes32}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
b := inputs[0].([32]byte)
// Prefix "0x"
hexString := "0x" + hex.EncodeToString(b[:])
return []any{hexString}, nil
},
)
// toString(bytes): Convert bytes to string
contract.addMethod("toString", abi.Arguments{{Type: typeBytes}}, abi.Arguments{{Type: typeString}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
b := inputs[0].([]byte)
// Prefix "0x"
hexString := "0x" + hex.EncodeToString(b)
return []any{hexString}, nil
},
)
// parseBytes: Convert string to bytes
contract.addMethod("parseBytes", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeBytes}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
return []any{[]byte(inputs[0].(string))}, nil
},
)
// parseBytes32: Convert string to bytes32
contract.addMethod("parseBytes32", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeBytes32}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
bSlice := []byte(inputs[0].(string))
// Use a fixed array and copy the data over
var bArray [32]byte
copy(bArray[:], bSlice)
return []any{bArray}, nil
},
)
// parseAddress: Convert string to address
contract.addMethod("parseAddress", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeAddress}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
addr, err := utils.HexStringToAddress(inputs[0].(string))
if err != nil {
return nil, cheatCodeRevertData([]byte("parseAddress: malformed string"))
}
return []any{addr}, nil
},
)
// parseUint: Convert string to uint256
contract.addMethod("parseUint", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeUint256}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
n, ok := new(big.Int).SetString(inputs[0].(string), 10)
if !ok {
return nil, cheatCodeRevertData([]byte("parseUint: malformed string"))
}
return []any{n}, nil
},
)
// parseInt: Convert string to int256
contract.addMethod("parseInt", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeInt256}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
n, ok := new(big.Int).SetString(inputs[0].(string), 10)
if !ok {
return nil, cheatCodeRevertData([]byte("parseInt: malformed string"))
}
return []any{n}, nil
},
)
// parseBool: Convert string to bool
contract.addMethod("parseBool", abi.Arguments{{Type: typeString}}, abi.Arguments{{Type: typeBool}},
func(tracer *cheatCodeTracer, inputs []any) ([]any, *cheatCodeRawReturnData) {
b, err := strconv.ParseBool(inputs[0].(string))
if err != nil {
return nil, cheatCodeRevertData([]byte("parseBool: malformed string"))
}
return []any{b}, nil
},
)
// Return our precompile contract information.
return contract, nil
}