1use fuels_core::{
2 types::{
3 errors::Result,
4 transaction::Transaction,
5 transaction_builders::{Blob, BlobTransactionBuilder},
6 tx_response::TxResponse,
7 },
8 Configurables,
9};
10
11use crate::assembly::script_and_predicate_loader::{
12 extract_data_offset, has_configurables_section_offset,
13};
14use crate::{
15 assembly::script_and_predicate_loader::{extract_configurables_offset, LoaderCode},
16 DEFAULT_MAX_FEE_ESTIMATION_TOLERANCE,
17};
18
19#[derive(Debug, Clone, PartialEq)]
21pub struct Regular {
22 code: Vec<u8>,
23 configurables: Configurables,
24}
25
26impl Regular {
27 pub fn new(code: Vec<u8>, configurables: Configurables) -> Self {
28 Self {
29 code,
30 configurables,
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq)]
39pub struct Executable<State> {
40 state: State,
41}
42
43impl Executable<Regular> {
44 pub fn from_bytes(code: Vec<u8>) -> Self {
45 Executable {
46 state: Regular::new(code, Default::default()),
47 }
48 }
49
50 pub fn load_from(path: &str) -> Result<Executable<Regular>> {
60 let code = std::fs::read(path)?;
61
62 Ok(Executable {
63 state: Regular::new(code, Default::default()),
64 })
65 }
66
67 pub fn with_configurables(self, configurables: impl Into<Configurables>) -> Self {
68 Executable {
69 state: Regular {
70 configurables: configurables.into(),
71 ..self.state
72 },
73 }
74 }
75
76 pub fn data_offset_in_code(&self) -> Result<usize> {
77 extract_data_offset(&self.state.code)
78 }
79
80 pub fn configurables_offset_in_code(&self) -> Result<Option<usize>> {
81 if has_configurables_section_offset(&self.state.code)? {
82 Ok(Some(extract_configurables_offset(&self.state.code)?))
83 } else {
84 Ok(None)
85 }
86 }
87
88 pub fn code(&self) -> Vec<u8> {
94 let mut code = self.state.code.clone();
95 self.state.configurables.update_constants_in(&mut code);
96 code
97 }
98
99 pub fn convert_to_loader(self) -> Result<Executable<Loader>> {
106 validate_loader_can_be_made_from_code(
107 self.state.code.clone(),
108 self.state.configurables.clone(),
109 )?;
110
111 Ok(Executable {
112 state: Loader {
113 code: self.state.code,
114 configurables: self.state.configurables,
115 },
116 })
117 }
118}
119
120pub struct Loader {
121 code: Vec<u8>,
122 configurables: Configurables,
123}
124
125impl Executable<Loader> {
126 pub fn with_configurables(self, configurables: impl Into<Configurables>) -> Self {
127 Executable {
128 state: Loader {
129 configurables: configurables.into(),
130 ..self.state
131 },
132 }
133 }
134
135 #[deprecated(note = "Use `configurables_offset_in_code` instead")]
136 pub fn data_offset_in_code(&self) -> usize {
137 self.loader_code().configurables_section_offset()
138 }
139
140 pub fn configurables_offset_in_code(&self) -> usize {
141 self.loader_code().configurables_section_offset()
142 }
143
144 fn loader_code(&self) -> LoaderCode {
145 let mut code = self.state.code.clone();
146
147 self.state.configurables.update_constants_in(&mut code);
148
149 LoaderCode::from_normal_binary(code)
150 .expect("checked before turning into a Executable<Loader>")
151 }
152
153 pub fn code(&self) -> Vec<u8> {
155 self.loader_code().as_bytes().to_vec()
156 }
157
158 pub fn blob(&self) -> Blob {
160 LoaderCode::extract_blob(&self.state.code)
163 .expect("checked before turning into a Executable<Loader>")
164 }
165
166 pub async fn upload_blob(
168 &self,
169 account: impl fuels_accounts::Account,
170 ) -> Result<Option<TxResponse>> {
171 let blob = self.blob();
172 let provider = account.try_provider()?;
173 let consensus_parameters = provider.consensus_parameters().await?;
174
175 if provider.blob_exists(blob.id()).await? {
176 return Ok(None);
177 }
178
179 let mut tb = BlobTransactionBuilder::default()
180 .with_blob(self.blob())
181 .with_max_fee_estimation_tolerance(DEFAULT_MAX_FEE_ESTIMATION_TOLERANCE);
182
183 account.adjust_for_fee(&mut tb, 0).await?;
184 account.add_witnesses(&mut tb)?;
185
186 let tx = tb.build(provider).await?;
187 let tx_id = tx.id(consensus_parameters.chain_id());
188
189 let tx_status = provider.send_transaction_and_await_commit(tx).await?;
190
191 Ok(Some(TxResponse {
192 tx_status: tx_status.take_success_checked(None)?,
193 tx_id,
194 }))
195 }
196}
197
198fn validate_loader_can_be_made_from_code(
199 mut code: Vec<u8>,
200 configurables: Configurables,
201) -> Result<()> {
202 configurables.update_constants_in(&mut code);
203
204 let _ = LoaderCode::from_normal_binary(code)?;
205
206 Ok(())
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use fuels_core::Configurables;
213 use std::io::Write;
214 use tempfile::NamedTempFile;
215
216 fn legacy_indicating_instruction() -> Vec<u8> {
217 fuel_asm::op::jmpf(0x0, 0x02).to_bytes().to_vec()
218 }
219
220 #[test]
221 fn test_executable_regular_from_bytes() {
222 let code = vec![1u8, 2, 3, 4];
224
225 let executable = Executable::<Regular>::from_bytes(code.clone());
227
228 assert_eq!(executable.state.code, code);
230 assert_eq!(executable.state.configurables, Default::default());
231 }
232
233 #[test]
234 fn test_executable_regular_load_from() {
235 let code = vec![5u8, 6, 7, 8];
237 let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
238 temp_file
239 .write_all(&code)
240 .expect("Failed to write to temp file");
241 let path = temp_file.path().to_str().unwrap();
242
243 let executable_result = Executable::<Regular>::load_from(path);
245
246 assert!(executable_result.is_ok());
248 let executable = executable_result.unwrap();
249 assert_eq!(executable.state.code, code);
250 assert_eq!(executable.state.configurables, Default::default());
251 }
252
253 #[test]
254 fn test_executable_regular_load_from_invalid_path() {
255 let invalid_path = "/nonexistent/path/to/file";
257
258 let executable_result = Executable::<Regular>::load_from(invalid_path);
260
261 assert!(executable_result.is_err());
263 }
264
265 #[test]
266 fn test_executable_regular_with_configurables() {
267 let code = vec![1u8, 2, 3, 4];
269 let executable = Executable::<Regular>::from_bytes(code);
270 let configurables = Configurables::new(vec![(2, vec![1])]);
271
272 let new_executable = executable.with_configurables(configurables.clone());
274
275 assert_eq!(new_executable.state.configurables, configurables);
277 }
278
279 #[test]
280 fn test_executable_regular_code() {
281 let code = vec![1u8, 2, 3, 4];
283 let configurables = Configurables::new(vec![(1, vec![1])]);
284 let executable =
285 Executable::<Regular>::from_bytes(code.clone()).with_configurables(configurables);
286
287 let modified_code = executable.code();
289
290 assert_eq!(modified_code, vec![1, 1, 3, 4]);
291 }
292
293 #[test]
294 fn test_loader_extracts_code_and_data_section_legacy_format() {
295 let padding = vec![0; 4];
296 let jmpf = legacy_indicating_instruction();
297 let data_offset = 28u64.to_be_bytes().to_vec();
298 let remaining_padding = vec![0; 8];
299 let some_random_instruction = vec![1, 2, 3, 4];
300 let data_section = vec![5, 6, 7, 8];
301
302 let code = [
303 padding.clone(),
304 jmpf.clone(),
305 data_offset.clone(),
306 remaining_padding.clone(),
307 some_random_instruction.clone(),
308 data_section.clone(),
309 ]
310 .concat();
311
312 let executable = Executable::<Regular>::from_bytes(code.clone());
313
314 let loader = executable.convert_to_loader().unwrap();
315
316 let blob = loader.blob();
317 let data_stripped_code = [
318 padding,
319 jmpf.clone(),
320 data_offset,
321 remaining_padding.clone(),
322 some_random_instruction,
323 ]
324 .concat();
325 assert_eq!(blob.as_ref(), data_stripped_code);
326
327 let loader_code = loader.code();
329
330 assert_eq!(
331 loader_code,
332 LoaderCode::from_normal_binary(code).unwrap().as_bytes()
333 );
334 }
335
336 #[test]
337 fn test_loader_extracts_code_and_configurable_section_new_format() {
338 let padding = vec![0; 4];
339 let jmpf = legacy_indicating_instruction();
340 let data_offset = 28u64.to_be_bytes().to_vec();
341 let configurable_offset = vec![0; 8];
342 let data_section = vec![5, 6, 7, 8];
343 let configurable_section = vec![9, 9, 9, 9];
344
345 let code = [
346 padding.clone(),
347 jmpf.clone(),
348 data_offset.clone(),
349 configurable_offset.clone(),
350 data_section.clone(),
351 configurable_section,
352 ]
353 .concat();
354
355 let executable = Executable::<Regular>::from_bytes(code.clone());
356
357 let loader = executable.convert_to_loader().unwrap();
358
359 let blob = loader.blob();
360 let configurable_stripped_code = [
361 padding,
362 jmpf,
363 data_offset,
364 configurable_offset,
365 data_section,
366 ]
367 .concat();
368 assert_eq!(blob.as_ref(), configurable_stripped_code);
369
370 let loader_code = loader.code();
372 assert_eq!(
373 loader_code,
374 LoaderCode::from_normal_binary(code).unwrap().as_bytes()
375 );
376 }
377
378 #[test]
379 fn test_executable_regular_convert_to_loader_with_invalid_code() {
380 let code = vec![1u8, 2]; let executable = Executable::<Regular>::from_bytes(code);
383
384 let result = executable.convert_to_loader();
386
387 assert!(result.is_err());
389 }
390
391 #[test]
392 fn executable_with_no_data_section() {
393 let data_section_offset = 16u64;
396
397 let jmpf = legacy_indicating_instruction();
398 let mut initial_bytes = vec![0; 16];
399 initial_bytes[4..8].copy_from_slice(&jmpf);
400
401 let code = [initial_bytes, data_section_offset.to_be_bytes().to_vec()].concat();
402
403 Executable::from_bytes(code).convert_to_loader().unwrap();
404 }
405}