fuels_programs/
executable.rs

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/// This struct represents a standard executable with its associated bytecode and configurables.
20#[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/// Used to transform Script or Predicate code into a loader variant, where the code is uploaded as
36/// a blob and the binary itself is substituted with code that will load the blob code and apply
37/// the given configurables to the Script/Predicate.
38#[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    /// Loads an `Executable<Regular>` from a file at the given path.
51    ///
52    /// # Parameters
53    ///
54    /// - `path`: The file path to load the executable from.
55    ///
56    /// # Returns
57    ///
58    /// A `Result` containing the `Executable<Regular>` or an error if loading fails.
59    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    /// Returns the code of the executable with configurables applied.
89    ///
90    /// # Returns
91    ///
92    /// The bytecode of the executable with configurables updated.
93    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    /// Converts the `Executable<Regular>` into an `Executable<Loader>`.
100    ///
101    /// # Returns
102    ///
103    /// A `Result` containing the `Executable<Loader>` or an error if loader code cannot be
104    /// generated for the given binary.
105    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    /// Returns the code of the loader executable with configurables applied.
154    pub fn code(&self) -> Vec<u8> {
155        self.loader_code().as_bytes().to_vec()
156    }
157
158    /// A Blob containing the original executable code minus the data section.
159    pub fn blob(&self) -> Blob {
160        // we don't apply configurables because they touch the data section which isn't part of the
161        // blob
162        LoaderCode::extract_blob(&self.state.code)
163            .expect("checked before turning into a Executable<Loader>")
164    }
165
166    /// If not previously uploaded, uploads a blob containing the original executable code minus the data section.
167    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        // Given: Some bytecode
223        let code = vec![1u8, 2, 3, 4];
224
225        // When: Creating an Executable<Regular> from bytes
226        let executable = Executable::<Regular>::from_bytes(code.clone());
227
228        // Then: The executable should have the given code and default configurables
229        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        // Given: A temporary file containing some bytecode
236        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        // When: Loading an Executable<Regular> from the file
244        let executable_result = Executable::<Regular>::load_from(path);
245
246        // Then: The executable should be created successfully with the correct code
247        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        // Given: An invalid file path
256        let invalid_path = "/nonexistent/path/to/file";
257
258        // When: Attempting to load an Executable<Regular> from the invalid path
259        let executable_result = Executable::<Regular>::load_from(invalid_path);
260
261        // Then: The operation should fail with an error
262        assert!(executable_result.is_err());
263    }
264
265    #[test]
266    fn test_executable_regular_with_configurables() {
267        // Given: An Executable<Regular> and some configurables
268        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        // When: Setting new configurables
273        let new_executable = executable.with_configurables(configurables.clone());
274
275        // Then: The executable should have the new configurables
276        assert_eq!(new_executable.state.configurables, configurables);
277    }
278
279    #[test]
280    fn test_executable_regular_code() {
281        // Given: An Executable<Regular> with some code and configurables
282        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        // When: Retrieving the code after applying configurables
288        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        // And: Loader code should match expected binary
328        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        // And: Loader code should match expected binary
371        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        // Given: An Executable<Regular> with invalid code (too short)
381        let code = vec![1u8, 2]; // Insufficient length for a valid data offset
382        let executable = Executable::<Regular>::from_bytes(code);
383
384        // When: Attempting to convert to a loader
385        let result = executable.convert_to_loader();
386
387        // Then: The conversion should fail with an error
388        assert!(result.is_err());
389    }
390
391    #[test]
392    fn executable_with_no_data_section() {
393        // to skip over the first 2 half words and skip over the offset itself, basically stating
394        // that there is no data section
395        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}