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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#[cfg(not(feature = "legacy_encoding"))]
use std::collections::VecDeque;

use fuel_tx::{ContractId, Receipt};
#[cfg(feature = "legacy_encoding")]
use fuels_core::types::param_types::ReturnLocation;
use fuels_core::{
    codec::{ABIDecoder, DecoderConfig},
    types::{
        bech32::Bech32ContractId,
        errors::{error, Error, Result},
        param_types::ParamType,
        Token,
    },
};
#[cfg(feature = "legacy_encoding")]
use itertools::Itertools;

pub struct ReceiptParser {
    #[cfg(feature = "legacy_encoding")]
    receipts: Vec<Receipt>,
    #[cfg(not(feature = "legacy_encoding"))]
    receipts: VecDeque<Receipt>,
    decoder: ABIDecoder,
}

#[cfg(feature = "legacy_encoding")]
impl ReceiptParser {
    pub fn new(receipts: &[Receipt], decoder_config: DecoderConfig) -> Self {
        let relevant_receipts: Vec<Receipt> = receipts
            .iter()
            .filter(|receipt| {
                matches!(receipt, Receipt::ReturnData { .. } | Receipt::Return { .. })
            })
            .cloned()
            .collect();

        Self {
            receipts: relevant_receipts,
            decoder: ABIDecoder::new(decoder_config),
        }
    }

    /// Based on receipts returned by a script transaction, the contract ID (in the case of a contract call),
    /// and the output param, parse the values and return them as Token.
    pub fn parse(
        &mut self,
        contract_id: Option<&Bech32ContractId>,
        output_param: &ParamType,
    ) -> Result<Token> {
        let contract_id = contract_id
            .map(Into::into)
            // During a script execution, the script's contract id is the **null** contract id
            .unwrap_or_else(ContractId::zeroed);

        output_param.validate_is_decodable(self.decoder.config.max_depth)?;

        let data = self
            .extract_raw_data(output_param, &contract_id)
            .ok_or_else(|| Self::missing_receipts_error(output_param))?;

        self.decoder.decode(output_param, &data)
    }

    fn missing_receipts_error(output_param: &ParamType) -> Error {
        error!(
            Codec,
            "`ReceiptDecoder`: failed to find matching receipts entry for {output_param:?}"
        )
    }

    fn extract_raw_data(
        &mut self,
        output_param: &ParamType,
        contract_id: &ContractId,
    ) -> Option<Vec<u8>> {
        let extra_receipts_needed = output_param.is_extra_receipt_needed(true);

        match output_param.get_return_location() {
            ReturnLocation::ReturnData
                if extra_receipts_needed && matches!(output_param, ParamType::Enum { .. }) =>
            {
                self.extract_enum_heap_type_data(contract_id)
            }
            ReturnLocation::ReturnData if extra_receipts_needed => {
                self.extract_return_data_heap(contract_id)
            }
            ReturnLocation::ReturnData => self.extract_return_data(contract_id),
            ReturnLocation::Return => self.extract_return(contract_id),
        }
    }

    fn extract_enum_heap_type_data(&mut self, contract_id: &ContractId) -> Option<Vec<u8>> {
        for (index, (current_receipt, next_receipt)) in
            self.receipts.iter().tuple_windows().enumerate()
        {
            if let (Some(first_data), Some(second_data)) =
                Self::extract_heap_data_from_receipts(current_receipt, next_receipt, contract_id)
            {
                let mut first_data = first_data.clone();
                let mut second_data = second_data.clone();
                self.receipts.drain(index..=index + 1);
                first_data.append(&mut second_data);

                return Some(first_data);
            }
        }
        None
    }

    fn extract_return_data(&mut self, contract_id: &ContractId) -> Option<Vec<u8>> {
        for (index, receipt) in self.receipts.iter_mut().enumerate() {
            if let Receipt::ReturnData {
                id,
                data: Some(data),
                ..
            } = receipt
            {
                if id == contract_id {
                    let data = std::mem::take(data);
                    self.receipts.remove(index);
                    return Some(data);
                }
            }
        }
        None
    }

    fn extract_return(&mut self, contract_id: &ContractId) -> Option<Vec<u8>> {
        for (index, receipt) in self.receipts.iter_mut().enumerate() {
            if let Receipt::Return { id, val, .. } = receipt {
                if *id == *contract_id {
                    let data = val.to_be_bytes().to_vec();
                    self.receipts.remove(index);
                    return Some(data);
                }
            }
        }
        None
    }

    fn extract_return_data_heap(&mut self, contract_id: &ContractId) -> Option<Vec<u8>> {
        // If the output of the function is a vector, then there are 2 consecutive ReturnData
        // receipts. The first one is the one that returns the pointer to the vec struct in the
        // VM memory, the second one contains the actual vector bytes (that the previous receipt
        // points to).
        // We ensure to take the right "first" ReturnData receipt by checking for the
        // contract_id. There are no receipts in between the two ReturnData receipts because of
        // the way the scripts are built (the calling script adds a RETD just after the CALL
        // opcode, see `get_single_call_instructions`).
        for (index, (current_receipt, next_receipt)) in
            self.receipts.iter().tuple_windows().enumerate()
        {
            if let (_stack_data, Some(heap_data)) =
                Self::extract_heap_data_from_receipts(current_receipt, next_receipt, contract_id)
            {
                let data = heap_data.clone();
                self.receipts.drain(index..=index + 1);
                return Some(data);
            }
        }
        None
    }

    fn extract_heap_data_from_receipts<'a>(
        current_receipt: &'a Receipt,
        next_receipt: &'a Receipt,
        contract_id: &ContractId,
    ) -> (Option<&'a Vec<u8>>, Option<&'a Vec<u8>>) {
        match (current_receipt, next_receipt) {
            (
                Receipt::ReturnData {
                    id: first_id,
                    data: first_data,
                    ..
                },
                Receipt::ReturnData {
                    id: second_id,
                    data: vec_data,
                    ..
                },
            ) if *first_id == *contract_id
                && first_data.is_some()
                // The second ReturnData receipt was added by a script instruction, its contract id
                // is null
                && *second_id == ContractId::zeroed() =>
            {
                (first_data.as_ref(), vec_data.as_ref())
            }
            _ => (None, None),
        }
    }
}

#[cfg(not(feature = "legacy_encoding"))]
impl ReceiptParser {
    pub fn new(receipts: &[Receipt], decoder_config: DecoderConfig) -> Self {
        let relevant_receipts = receipts
            .iter()
            .filter(|receipt| matches!(receipt, Receipt::ReturnData { .. } | Receipt::Call { .. }))
            .cloned()
            .collect();

        Self {
            receipts: relevant_receipts,
            decoder: ABIDecoder::new(decoder_config),
        }
    }

    /// Based on receipts returned by a script transaction, the contract ID,
    /// and the output param, parse the values and return them as Token.
    pub fn parse_call(
        &mut self,
        contract_id: &Bech32ContractId,
        output_param: &ParamType,
    ) -> Result<Token> {
        let data = self
            .extract_contract_call_data(contract_id.into())
            .ok_or_else(|| Self::missing_receipts_error(output_param))?;

        self.decoder.decode(output_param, &data)
    }

    pub fn parse_script(self, output_param: &ParamType) -> Result<Token> {
        let data = self
            .extract_script_data()
            .ok_or_else(|| Self::missing_receipts_error(output_param))?;

        self.decoder.decode(output_param, &data)
    }

    fn missing_receipts_error(output_param: &ParamType) -> Error {
        error!(
            Codec,
            "`ReceiptDecoder`: failed to find matching receipts entry for {output_param:?}"
        )
    }

    fn extract_contract_call_data(&mut self, target_contract: ContractId) -> Option<Vec<u8>> {
        // If the script contains nested calls, we need to extract the data of the top-level call
        let mut nested_calls_stack = vec![];

        while let Some(receipt) = self.receipts.pop_front() {
            if let Receipt::Call { to, .. } = receipt {
                nested_calls_stack.push(to);
            } else if let Receipt::ReturnData {
                data,
                id: return_id,
                ..
            } = receipt
            {
                let call_id = nested_calls_stack.pop();

                // Somethings off if there is a mismatch between the call and return ids
                debug_assert_eq!(call_id.unwrap(), return_id);

                if nested_calls_stack.is_empty() {
                    // The top-level call return should match our target contract
                    debug_assert_eq!(target_contract, return_id);

                    return data.clone();
                }
            }
        }

        None
    }

    fn extract_script_data(&self) -> Option<Vec<u8>> {
        self.receipts.iter().find_map(|receipt| match receipt {
            Receipt::ReturnData {
                id,
                data: Some(data),
                ..
            } if *id == ContractId::zeroed() => Some(data.clone()),
            _ => None,
        })
    }
}

#[cfg(feature = "legacy_encoding")]
#[cfg(test)]
mod tests {
    use fuel_tx::ScriptExecutionResult;
    use fuels_core::traits::{Parameterize, Tokenizable};

    use super::*;

    const RECEIPT_VAL: u64 = 225;
    const RECEIPT_DATA: &[u8; 3] = &[8, 8, 3];
    const DECODED_DATA: &[u8; 3] = &[8, 8, 3];

    fn target_contract() -> ContractId {
        ContractId::from([1u8; 32])
    }

    fn get_return_receipt(id: ContractId, val: u64) -> Receipt {
        Receipt::Return {
            id,
            val,
            pc: Default::default(),
            is: Default::default(),
        }
    }

    fn get_return_data_receipt(id: ContractId, data: &[u8]) -> Receipt {
        Receipt::ReturnData {
            id,
            ptr: Default::default(),
            len: Default::default(),
            digest: Default::default(),
            data: Some(data.to_vec()),
            pc: Default::default(),
            is: Default::default(),
        }
    }

    fn get_relevant_receipts() -> Vec<Receipt> {
        vec![
            get_return_receipt(Default::default(), Default::default()),
            get_return_data_receipt(Default::default(), Default::default()),
        ]
    }

    #[tokio::test]
    async fn receipt_parser_filters_receipts() -> Result<()> {
        let mut receipts = vec![
            Receipt::Call {
                id: Default::default(),
                to: Default::default(),
                amount: Default::default(),
                asset_id: Default::default(),
                gas: Default::default(),
                param1: Default::default(),
                param2: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::Revert {
                id: Default::default(),
                ra: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::Log {
                id: Default::default(),
                ra: Default::default(),
                rb: Default::default(),
                rc: Default::default(),
                rd: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::LogData {
                id: Default::default(),
                ra: Default::default(),
                rb: Default::default(),
                ptr: Default::default(),
                len: Default::default(),
                digest: Default::default(),
                data: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::ScriptResult {
                result: ScriptExecutionResult::Success,
                gas_used: Default::default(),
            },
        ];
        let relevant_receipts = get_relevant_receipts();
        receipts.extend(relevant_receipts.clone());

        let parser = ReceiptParser::new(&receipts, Default::default());

        assert_eq!(parser.receipts, relevant_receipts);

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_empty_receipts() -> Result<()> {
        let receipts = [];
        let output_param = ParamType::Unit;

        let error = ReceiptParser::new(&receipts, Default::default())
            .parse(Default::default(), &output_param)
            .expect_err("should error");

        let expected_error = ReceiptParser::missing_receipts_error(&output_param);
        assert_eq!(error.to_string(), expected_error.to_string());

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_extract_return_data() -> Result<()> {
        let expected_receipts = get_relevant_receipts();
        let contract_id = target_contract();

        let mut receipts = expected_receipts.clone();
        receipts.push(get_return_data_receipt(contract_id, RECEIPT_DATA));
        let mut parser = ReceiptParser::new(&receipts, Default::default());

        let token = parser
            .parse(Some(&contract_id.into()), &<[u8; 3]>::param_type())
            .expect("parsing should succeed");

        assert_eq!(&<[u8; 3]>::from_token(token)?, DECODED_DATA);
        assert_eq!(parser.receipts, expected_receipts);

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_extract_return() -> Result<()> {
        let expected_receipts = get_relevant_receipts();
        let contract_id = target_contract();

        let mut receipts = expected_receipts.clone();
        #[cfg(feature = "legacy_encoding")]
        receipts.push(get_return_receipt(contract_id, RECEIPT_VAL));
        #[cfg(not(feature = "legacy_encoding"))] // all data is returned as RETD
        receipts.push(get_return_data_receipt(
            contract_id,
            &RECEIPT_VAL.to_be_bytes(),
        ));
        let mut parser = ReceiptParser::new(&receipts, Default::default());

        let token = parser
            .parse(Some(&contract_id.into()), &u64::param_type())
            .expect("parsing should succeed");

        assert_eq!(u64::from_token(token)?, RECEIPT_VAL);
        assert_eq!(parser.receipts, expected_receipts);

        Ok(())
    }

    #[cfg(feature = "legacy_encoding")]
    #[tokio::test]
    async fn receipt_parser_extract_return_data_heap() -> Result<()> {
        let expected_receipts = get_relevant_receipts();
        let contract_id = target_contract();

        let mut receipts = expected_receipts.clone();
        receipts.push(get_return_data_receipt(target_contract(), &[9, 9, 9]));
        receipts.push(get_return_data_receipt(Default::default(), RECEIPT_DATA));
        let mut parser = ReceiptParser::new(&receipts, Default::default());

        let token = parser
            .parse(Some(&contract_id.into()), &<Vec<u8>>::param_type())
            .expect("parsing should succeed");

        assert_eq!(&<Vec<u8>>::from_token(token)?, DECODED_DATA);
        assert_eq!(parser.receipts, expected_receipts);

        Ok(())
    }
}

#[cfg(not(feature = "legacy_encoding"))]
#[cfg(test)]
mod tests {
    use fuel_tx::ScriptExecutionResult;
    use fuels_core::traits::{Parameterize, Tokenizable};

    use super::*;

    const RECEIPT_DATA: &[u8; 3] = &[8, 8, 3];
    const DECODED_DATA: &[u8; 3] = &[8, 8, 3];

    fn target_contract() -> ContractId {
        ContractId::from([1u8; 32])
    }

    fn get_return_data_receipt(id: ContractId, data: &[u8]) -> Receipt {
        Receipt::ReturnData {
            id,
            ptr: Default::default(),
            len: Default::default(),
            digest: Default::default(),
            data: Some(data.to_vec()),
            pc: Default::default(),
            is: Default::default(),
        }
    }

    fn get_call_receipt(to: ContractId) -> Receipt {
        Receipt::Call {
            id: Default::default(),
            to,
            amount: Default::default(),
            asset_id: Default::default(),
            gas: Default::default(),
            param1: Default::default(),
            param2: Default::default(),
            pc: Default::default(),
            is: Default::default(),
        }
    }

    fn get_relevant_receipts() -> Vec<Receipt> {
        let id = target_contract();
        vec![
            get_call_receipt(id),
            get_return_data_receipt(id, RECEIPT_DATA),
        ]
    }

    #[tokio::test]
    async fn receipt_parser_filters_receipts() -> Result<()> {
        let mut receipts = vec![
            Receipt::Revert {
                id: Default::default(),
                ra: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::Log {
                id: Default::default(),
                ra: Default::default(),
                rb: Default::default(),
                rc: Default::default(),
                rd: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::LogData {
                id: Default::default(),
                ra: Default::default(),
                rb: Default::default(),
                ptr: Default::default(),
                len: Default::default(),
                digest: Default::default(),
                data: Default::default(),
                pc: Default::default(),
                is: Default::default(),
            },
            Receipt::ScriptResult {
                result: ScriptExecutionResult::Success,
                gas_used: Default::default(),
            },
        ];
        let relevant_receipts = get_relevant_receipts();
        receipts.extend(relevant_receipts.clone());

        let parser = ReceiptParser::new(&receipts, Default::default());

        assert_eq!(parser.receipts, relevant_receipts);

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_empty_receipts() -> Result<()> {
        let receipts = [];
        let output_param = ParamType::U8;

        let error = ReceiptParser::new(&receipts, Default::default())
            .parse_call(&target_contract().into(), &output_param)
            .expect_err("should error");

        let expected_error = ReceiptParser::missing_receipts_error(&output_param);
        assert_eq!(error.to_string(), expected_error.to_string());

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_extract_return_data() -> Result<()> {
        let receipts = get_relevant_receipts();
        let contract_id = target_contract();

        let mut parser = ReceiptParser::new(&receipts, Default::default());

        let token = parser
            .parse_call(&contract_id.into(), &<[u8; 3]>::param_type())
            .expect("parsing should succeed");

        assert_eq!(&<[u8; 3]>::from_token(token)?, DECODED_DATA);

        Ok(())
    }

    #[tokio::test]
    async fn receipt_parser_extracts_top_level_call_receipts() -> Result<()> {
        const CORRECT_DATA_1: [u8; 3] = [1, 2, 3];
        const CORRECT_DATA_2: [u8; 3] = [5, 6, 7];

        let contract_top_lvl = target_contract();
        let contract_nested = ContractId::from([9u8; 32]);

        let receipts = vec![
            get_call_receipt(contract_top_lvl),
            get_call_receipt(contract_nested),
            get_return_data_receipt(contract_nested, &[9, 9, 9]),
            get_return_data_receipt(contract_top_lvl, &CORRECT_DATA_1),
            get_call_receipt(contract_top_lvl),
            get_call_receipt(contract_nested),
            get_return_data_receipt(contract_nested, &[7, 7, 7]),
            get_return_data_receipt(contract_top_lvl, &CORRECT_DATA_2),
        ];

        let mut parser = ReceiptParser::new(&receipts, Default::default());

        let token_1 = parser
            .parse_call(&contract_top_lvl.into(), &<[u8; 3]>::param_type())
            .expect("parsing should succeed");
        let token_2 = parser
            .parse_call(&contract_top_lvl.into(), &<[u8; 3]>::param_type())
            .expect("parsing should succeed");

        assert_eq!(&<[u8; 3]>::from_token(token_1)?, &CORRECT_DATA_1);
        assert_eq!(&<[u8; 3]>::from_token(token_2)?, &CORRECT_DATA_2);

        Ok(())
    }
}