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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use t3rn_types::sfx::*;

use codec::{Decode, Encode};
use sp_runtime::{traits::Zero, RuntimeDebug};
use sp_std::vec::Vec;

pub type XtxId<T> = <T as frame_system::Config>::Hash;
pub use crate::volatile::{LocalState, Volatile};

use scale_info::TypeInfo;
use sp_std::fmt::Debug;

/// A composable cross-chain (X) transaction that has already been verified to be valid and submittable
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct Xtx<AccountId, BlockNumber, BalanceOf> {
    // todo: Add missing DFDs
    // pub contracts_dfd: InterExecSchedule -> ContractsDFD
    // pub side_effects_dfd: SideEffectsDFD
    // pub gateways_dfd: GatewaysDFD
    /// The owner of the bid
    pub requester: AccountId,

    /// Encoded content of composable tx
    pub initial_input: Vec<u8>,

    /// Expiry timeout
    pub timeouts_at: Option<BlockNumber>,

    /// Schedule execution of steps in the future intervals
    pub delay_steps_at: Option<Vec<BlockNumber>>,

    /// Has returned status already and what
    pub result_status: Option<Vec<u8>>,

    /// Total reward
    pub total_reward: Option<BalanceOf>,

    /// Local Xtx State
    pub local_state: LocalState,

    /// Vector of Steps that each can consist out of at least one FullSideEffect
    pub full_side_effects: Vec<Vec<FullSideEffect<AccountId, BlockNumber, BalanceOf>>>,
}

impl<
        AccountId: Encode + Clone + Debug,
        BlockNumber: Ord + Copy + Zero + Encode + Clone + Debug,
        BalanceOf: Copy + Zero + Encode + Decode + Clone + Debug,
    > Xtx<AccountId, BlockNumber, BalanceOf>
{
    pub fn new(
        // Requester of xtx
        requester: AccountId,
        // Encoded initial input set by a requester/SDK - base for the xtx state
        initial_input: Vec<u8>,
        // Expiry timeout
        timeouts_at: Option<BlockNumber>,
        // Schedule execution of steps in the future intervals
        delay_steps_at: Option<Vec<BlockNumber>>,
        // Total reward
        total_reward: Option<BalanceOf>,
        local_state: LocalState,
        full_side_effects: Vec<Vec<FullSideEffect<AccountId, BlockNumber, BalanceOf>>>,
    ) -> Self {
        Xtx {
            requester,
            initial_input,
            timeouts_at,
            delay_steps_at,
            result_status: None,
            total_reward,
            local_state,
            full_side_effects,
        }
    }

    pub fn generate_xtx_id<Hasher: sp_core::Hasher>(
        &self,
        requester_nonce: u32,
    ) -> <Hasher as sp_core::Hasher>::Out {
        let mut requester_on_32b_as_vec = self.requester.encode();

        let nonce_as_4b_word: [u8; 4] = requester_nonce.to_be_bytes();
        let mut nonce_as_32b_word: [u8; 32];
        nonce_as_32b_word = [0; 32];
        nonce_as_32b_word[28..32].copy_from_slice(&nonce_as_4b_word);
        requester_on_32b_as_vec.extend_from_slice(&nonce_as_32b_word);

        Hasher::hash(requester_on_32b_as_vec.as_slice())
    }

    pub fn is_completed(&self) -> bool {
        for step in self.full_side_effects.iter() {
            for full_side_effect in step.iter() {
                if full_side_effect.confirmed.is_none() {
                    return false
                }
            }
        }
        true
    }

    // Complete the full side effect of Xtx by assigning confirmed side effect/
    // This can only happen if the side effects is confirmed with respect to
    // the execution steps.
    //
    // Return true if the input side effect successfully confirmed.
    // Return false if no update has happened.
    // Throw an error if detected the confirmation ruleset has been violated.
    pub fn complete_side_effect<Hasher: sp_core::Hasher>(
        &mut self,
        confirmed: ConfirmedSideEffect<AccountId, BlockNumber, BalanceOf>,
        input: SideEffect<AccountId, BalanceOf>,
        xtx_id: <Hasher as sp_core::Hasher>::Out,
        sfx_index: u32,
    ) -> Result<bool, &'static str> {
        let sfx_id = input.generate_id::<Hasher>(xtx_id.as_ref(), sfx_index);

        // Double check there are some side effects for that Xtx - should have been checked at API level tho already
        if self.full_side_effects.is_empty() {
            return Err("Xtx has no single side effect step to confirm")
        }

        let mut unconfirmed_step_no: Option<usize> = None;

        for (i, step) in self.full_side_effects.iter_mut().enumerate() {
            // Double check there are some side effects for that Xtx - should have been checked at API level tho already
            if step.is_empty() {
                return Err("Xtx has an empty single step.")
            }
            for full_side_effect in step.iter_mut() {
                if full_side_effect.confirmed.is_none() {
                    // Mark the first step no with encountered unconfirmed side effect
                    if unconfirmed_step_no.is_none() {
                        unconfirmed_step_no = Some(i);
                    }

                    // Recalculate the ID for each input side effect and compare with the input one.
                    // Check the current unconfirmed step before attempt to confirm the full side effect.
                    return if full_side_effect
                        .input
                        .generate_id::<Hasher>(xtx_id.as_ref(), full_side_effect.index)
                        == sfx_id
                        && unconfirmed_step_no == Some(i)
                    {
                        // We found the side effect to confirm from inside the unconfirmed step.
                        full_side_effect.confirmed = Some(confirmed);
                        Ok(true)
                    } else {
                        Err("Attempt to confirm side effect from the next step, \
                                but there still is at least one unfinished step")
                    }
                }
            }
        }

        Ok(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    type BlockNumber = u32;
    type BalanceOf = u64;
    type AccountId = u64;
    type Hashing = sp_runtime::traits::BlakeTwo256;

    #[test]
    fn successfully_creates_empty_xtx() {
        let empty_xtx = Xtx::<AccountId, BlockNumber, BalanceOf>::new(
            0,
            vec![],
            None,
            None,
            None,
            LocalState::new(),
            vec![],
        );

        assert_eq!(
            empty_xtx,
            Xtx {
                requester: 0,
                initial_input: vec![],
                timeouts_at: None,
                delay_steps_at: None,
                result_status: None,
                total_reward: None,
                local_state: LocalState::new(),
                full_side_effects: vec![],
            }
        );
    }

    #[test]
    fn successfully_confirms_1_side_effect_and_completes_xtx() {
        let input_side_effect_1 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 0],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let completing_side_effect_1 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 1,
            received_at: 1,
            cost: None,
        };

        let mut xtx = Xtx::<AccountId, BlockNumber, BalanceOf>::new(
            0,
            vec![],
            None,
            None,
            None,
            LocalState::new(),
            vec![vec![FullSideEffect {
                input: input_side_effect_1.clone(),
                confirmed: None,
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 0,
            }]],
        );

        assert!(!xtx.is_completed());

        let res = xtx
            .complete_side_effect::<Hashing>(
                completing_side_effect_1.clone(),
                input_side_effect_1.clone(),
                xtx.generate_xtx_id::<Hashing>(0),
                0,
            )
            .unwrap();

        assert!(res);
        // Check that xtx.full_side_effects has been updated
        assert_eq!(
            xtx.full_side_effects[0][0],
            FullSideEffect {
                input: input_side_effect_1,
                confirmed: Some(completing_side_effect_1),
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 0
            }
        );

        assert!(xtx.is_completed());
    }

    #[test]
    fn successfully_confirms_2_side_effect_in_1_step_in_xtx() {
        let input_side_effect_1 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 0],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let input_side_effect_2 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 1],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let completing_side_effect_1 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 1,
            received_at: 1,
            cost: None,
        };

        let completing_side_effect_2 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 2,
            received_at: 1,
            cost: None,
        };

        let mut xtx = Xtx::<AccountId, BlockNumber, BalanceOf>::new(
            0,
            vec![],
            None,
            None,
            None,
            LocalState::new(),
            vec![vec![
                FullSideEffect {
                    input: input_side_effect_1.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 0,
                },
                FullSideEffect {
                    input: input_side_effect_2.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 1,
                },
            ]],
        );

        let res_1 = xtx
            .complete_side_effect::<Hashing>(
                completing_side_effect_1.clone(),
                input_side_effect_1.clone(),
                xtx.generate_xtx_id::<Hashing>(1),
                0,
            )
            .unwrap();

        assert!(res_1);
        // Check that the first xtx.full_side_effects has been updated
        assert_eq!(
            xtx.full_side_effects[0][0],
            FullSideEffect {
                input: input_side_effect_1,
                confirmed: Some(completing_side_effect_1),
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 0
            }
        );

        // Check that the second xtx.full_side_effects has NOT been updated
        assert_eq!(
            xtx.full_side_effects[0][1],
            FullSideEffect {
                input: input_side_effect_2.clone(),
                confirmed: None,
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 1
            }
        );

        assert!(!xtx.is_completed());

        let res_2 = xtx
            .complete_side_effect::<Hashing>(
                completing_side_effect_2.clone(),
                input_side_effect_2.clone(),
                xtx.generate_xtx_id::<Hashing>(2),
                1,
            )
            .unwrap();

        assert!(res_2);

        // Check that the second xtx.full_side_effects has now been updated
        assert_eq!(
            xtx.full_side_effects[0][1],
            FullSideEffect {
                input: input_side_effect_2,
                confirmed: Some(completing_side_effect_2),
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 1
            }
        );
        assert!(xtx.is_completed());
    }

    #[test]
    fn successfully_confirms_2_side_effect_in_2_steps_in_xtx() {
        let input_side_effect_1 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 0],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let input_side_effect_2 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 1],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let completing_side_effect_1 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 1,
            received_at: 1,
            cost: None,
        };

        let completing_side_effect_2 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 2,
            received_at: 1,
            cost: None,
        };

        // This time Xtx contains 2 steps each consisting from 1 side effect
        let mut xtx = Xtx::<AccountId, BlockNumber, BalanceOf>::new(
            0,
            vec![],
            None,
            None,
            None,
            LocalState::new(),
            vec![
                vec![FullSideEffect {
                    input: input_side_effect_1.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 0,
                }],
                vec![FullSideEffect {
                    input: input_side_effect_2.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 1,
                }],
            ],
        );

        let res_1 = xtx
            .complete_side_effect::<Hashing>(
                completing_side_effect_1.clone(),
                input_side_effect_1.clone(),
                xtx.generate_xtx_id::<Hashing>(3),
                0,
            )
            .unwrap();

        assert!(res_1);
        // Check that the first xtx.full_side_effects has been updated
        assert_eq!(
            xtx.full_side_effects[0][0],
            FullSideEffect {
                input: input_side_effect_1,
                confirmed: Some(completing_side_effect_1),
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 0
            }
        );

        // Check that the second xtx.full_side_effects has NOT been updated
        assert_eq!(
            xtx.full_side_effects[1][0],
            FullSideEffect {
                input: input_side_effect_2.clone(),
                confirmed: None,
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 1
            }
        );

        let res_2 = xtx
            .complete_side_effect::<Hashing>(
                completing_side_effect_2.clone(),
                input_side_effect_2.clone(),
                xtx.generate_xtx_id::<Hashing>(4),
                1,
            )
            .unwrap();

        assert!(res_2);

        // Check that the second xtx.full_side_effects has now been updated
        assert_eq!(
            xtx.full_side_effects[1][0],
            FullSideEffect {
                input: input_side_effect_2,
                confirmed: Some(completing_side_effect_2),
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 1
            }
        );
        assert!(xtx.is_completed());
    }

    #[test]
    fn throws_when_attempts_to_confirm_side_effect_from_2nd_step_without_1st_in_xtx() {
        let input_side_effect_1 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 0],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let input_side_effect_2 = SideEffect::<AccountId, BalanceOf> {
            target: [0, 0, 0, 1],
            max_reward: 1,
            action: [0, 0, 0, 0],
            encoded_args: vec![],
            signature: vec![],
            insurance: 1,
            enforce_executor: None,
            reward_asset_id: None,
        };

        let _completing_side_effect_1 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 1,
            received_at: 1,
            cost: None,
        };

        let completing_side_effect_2 = ConfirmedSideEffect::<AccountId, BlockNumber, BalanceOf> {
            err: None,
            output: None,
            inclusion_data: vec![0],
            executioner: 2,
            received_at: 1,
            cost: None,
        };

        // This time Xtx contains 2 steps each consisting from 1 side effect
        let mut xtx = Xtx::<AccountId, BlockNumber, BalanceOf>::new(
            0,
            vec![],
            None,
            None,
            None,
            LocalState::new(),
            vec![
                vec![FullSideEffect {
                    input: input_side_effect_1.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 0,
                }],
                vec![FullSideEffect {
                    input: input_side_effect_2.clone(),
                    confirmed: None,
                    security_lvl: SecurityLvl::Optimistic,
                    submission_target_height: 1,
                    best_bid: None,
                    index: 1,
                }],
            ],
        );

        let res_2_err = xtx.complete_side_effect::<Hashing>(
            completing_side_effect_2,
            input_side_effect_2.clone(),
            xtx.generate_xtx_id::<Hashing>(5),
            1,
        );

        assert_eq!(res_2_err, Err("Attempt to confirm side effect from the next step, but there still is at least one unfinished step"));

        // Check that the firsts AND second xtx.full_side_effects has NOT been updated
        assert_eq!(
            xtx.full_side_effects[0][0],
            FullSideEffect {
                input: input_side_effect_1,
                confirmed: None,
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 0
            }
        );

        assert_eq!(
            xtx.full_side_effects[1][0],
            FullSideEffect {
                input: input_side_effect_2,
                confirmed: None,
                security_lvl: SecurityLvl::Optimistic,
                submission_target_height: 1,
                best_bid: None,
                index: 1
            }
        );

        assert!(!xtx.is_completed());
    }
}