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
mod jump_table;
use crate::{keccak256, B256, KECCAK_EMPTY};
use alloc::sync::Arc;
use bytes::Bytes;
pub use jump_table::{Analysis, AnalysisData, ValidJumpAddress};
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BytecodeState {
Raw,
Checked {
len: usize,
},
Analysed {
len: usize,
jumptable: ValidJumpAddress,
},
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Bytecode {
#[cfg_attr(feature = "serde", serde(with = "crate::utilities::serde_hex_bytes"))]
pub bytecode: Bytes,
pub hash: B256,
pub state: BytecodeState,
}
impl Default for Bytecode {
fn default() -> Self {
Bytecode::new()
}
}
impl Bytecode {
pub fn new() -> Self {
Bytecode {
bytecode: vec![0].into(),
hash: KECCAK_EMPTY,
state: BytecodeState::Analysed {
len: 0,
jumptable: ValidJumpAddress::new(Arc::new(vec![AnalysisData::none()]), 0),
},
}
}
pub fn new_raw(bytecode: Bytes) -> Self {
let hash = if bytecode.is_empty() {
KECCAK_EMPTY
} else {
keccak256(&bytecode)
};
Self {
bytecode,
hash,
state: BytecodeState::Raw,
}
}
pub unsafe fn new_raw_with_hash(bytecode: Bytes, hash: B256) -> Self {
Self {
bytecode,
hash,
state: BytecodeState::Raw,
}
}
pub unsafe fn new_checked(bytecode: Bytes, len: usize, hash: Option<B256>) -> Self {
let hash = match hash {
None if len == 0 => KECCAK_EMPTY,
None => keccak256(&bytecode),
Some(hash) => hash,
};
Self {
bytecode,
hash,
state: BytecodeState::Checked { len },
}
}
pub fn bytes(&self) -> &Bytes {
&self.bytecode
}
pub fn hash(&self) -> B256 {
self.hash
}
pub fn state(&self) -> &BytecodeState {
&self.state
}
pub fn is_empty(&self) -> bool {
match self.state {
BytecodeState::Raw => self.bytecode.is_empty(),
BytecodeState::Checked { len } => len == 0,
BytecodeState::Analysed { len, .. } => len == 0,
}
}
pub fn len(&self) -> usize {
match self.state {
BytecodeState::Raw => self.bytecode.len(),
BytecodeState::Checked { len, .. } => len,
BytecodeState::Analysed { len, .. } => len,
}
}
pub fn to_checked(self) -> Self {
match self.state {
BytecodeState::Raw => {
let len = self.bytecode.len();
let mut bytecode: Vec<u8> = Vec::from(self.bytecode.as_ref());
bytecode.resize(len + 33, 0);
Self {
bytecode: bytecode.into(),
hash: self.hash,
state: BytecodeState::Checked { len },
}
}
_ => self,
}
}
}