forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode-opcodes.ts
54 lines (42 loc) · 1.41 KB
/
decode-opcodes.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
// Decode opcodes example
//
// 1. Takes binary EVM code and decodes it into opcodes
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { getOpcodesForHF, paramsEVM } from '@ethereumjs/evm'
import { bytesToHex, hexToBytes } from '@ethereumjs/util'
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Istanbul, params: paramsEVM })
const opcodes = getOpcodesForHF(common).opcodes
const data = '0x6107608061000e6000396000f30060003560e060020a90048063141961bc1461006e57806319ac74bd'
nameOpCodes(hexToBytes(data))
function nameOpCodes(raw: Uint8Array) {
let pushData = new Uint8Array()
for (let i = 0; i < raw.length; i++) {
const pc = i
const curOpCode = opcodes.get(raw[pc])?.name
// no destinations into the middle of PUSH
if (curOpCode?.slice(0, 4) === 'PUSH') {
const jumpNum = raw[pc] - 0x5f
pushData = raw.subarray(pc + 1, pc + jumpNum + 1)
i += jumpNum
}
console.log(
pad(pc, roundLog(raw.length, 10)) +
' ' +
curOpCode +
' ' +
(pushData?.length > 0 ? bytesToHex(pushData as Uint8Array) : ''),
)
pushData = new Uint8Array()
}
}
function pad(num: number, size: number) {
let s = num + ''
while (s.length < size) s = '0' + s
return s
}
function log(num: number, base: number) {
return Math.log(num) / Math.log(base)
}
function roundLog(num: number, base: number) {
return Math.ceil(log(num, base))
}