fuel-core-txpool 0.48.0

Transaction pool that manages transactions and their dependencies.
Documentation
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::{
    collections::{
        HashMap,
        HashSet,
        VecDeque,
    },
    time::SystemTime,
};

use fuel_core_types::{
    fuel_tx::{
        ContractId,
        Input,
        Output,
        TxId,
        UtxoId,
        input::{
            coin::{
                CoinPredicate,
                CoinSigned,
            },
            contract::Contract,
            message::{
                MessageCoinPredicate,
                MessageCoinSigned,
                MessageDataPredicate,
                MessageDataSigned,
            },
        },
    },
    services::txpool::{
        ArcPoolTx,
        PoolTransaction,
    },
};
use petgraph::{
    graph::NodeIndex,
    prelude::StableDiGraph,
};

use crate::{
    error::{
        DependencyError,
        Error,
        InputValidationError,
        InputValidationErrorType,
    },
    extracted_outputs::ExtractedOutputs,
    pending_pool::MissingInput,
    ports::TxPoolPersistentStorage,
    selection_algorithms::ratio_tip_gas::RatioTipGasSelectionAlgorithmStorage,
    spent_inputs::SpentInputs,
    storage::checked_collision::CheckedTransaction,
};

use super::{
    RemovedTransactions,
    Storage,
    StorageData,
};

pub struct GraphStorage {
    /// The configuration of the graph
    config: GraphConfig,
    /// The graph of transactions
    graph: StableDiGraph<StorageData, ()>,
    /// Coins -> Transaction that currently create the UTXO
    coins_creators: HashMap<UtxoId, NodeIndex>,
    /// Contract -> Transaction that currently create the contract
    contracts_creators: HashMap<ContractId, NodeIndex>,
}

pub struct GraphConfig {
    /// The maximum number of transactions per dependency chain
    pub max_txs_chain_count: usize,
}

impl GraphStorage {
    /// Create a new graph storage
    pub fn new(config: GraphConfig) -> Self {
        Self {
            config,
            graph: StableDiGraph::new(),
            coins_creators: HashMap::new(),
            contracts_creators: HashMap::new(),
        }
    }

    #[cfg(test)]
    pub fn is_empty(&self) -> bool {
        self.graph.node_count() == 0
            && self.coins_creators.is_empty()
            && self.contracts_creators.is_empty()
    }
}

impl GraphStorage {
    fn reduce_dependencies_cumulative_gas_tip_and_chain_count(
        &mut self,
        root_id: NodeIndex,
        removed_node: &StorageData,
    ) {
        let Some(root) = self.graph.node_weight_mut(root_id) else {
            debug_assert!(false, "Node with id {:?} not found", root_id);
            return;
        };
        root.dependents_cumulative_gas = root
            .dependents_cumulative_gas
            .saturating_sub(removed_node.dependents_cumulative_gas);
        root.dependents_cumulative_tip = root
            .dependents_cumulative_tip
            .saturating_sub(removed_node.dependents_cumulative_tip);
        root.number_dependents_in_chain = root
            .number_dependents_in_chain
            .saturating_sub(removed_node.number_dependents_in_chain);
        root.dependents_cumulative_bytes_size = root
            .dependents_cumulative_bytes_size
            .saturating_sub(removed_node.dependents_cumulative_bytes_size);

        debug_assert!(root.dependents_cumulative_gas != 0);
        debug_assert!(root.number_dependents_in_chain != 0);
        debug_assert!(root.dependents_cumulative_bytes_size != 0);

        let dependencies: Vec<_> = self.get_direct_dependencies(root_id).collect();
        for dependency in dependencies {
            self.reduce_dependencies_cumulative_gas_tip_and_chain_count(
                dependency,
                removed_node,
            );
        }
    }

    /// Remove a node and all its dependent sub-graph.
    /// Edit the data of dependencies transactions accordingly.
    /// Returns the removed transactions.
    fn remove_node_and_dependent_sub_graph(
        &mut self,
        root_id: NodeIndex,
    ) -> Vec<StorageData> {
        self.bfs(root_id)
    }

    fn bfs(&mut self, root: NodeIndex) -> Vec<StorageData> {
        // The algorithm heavily rely on the property of not having
        // diamond dependencies. The `DependentTransactionIsADiamondDeath` error
        // helps to achieve this property.

        if !self.graph.contains_node(root) {
            return vec![];
        }

        let mut queue = VecDeque::new();
        #[cfg(test)]
        let mut nodes_in_queue = HashSet::new();
        let mut result = Vec::new();

        queue.push_back(root);
        #[cfg(test)]
        nodes_in_queue.insert(root);

        while let Some(remove) = queue.pop_front() {
            let dependents: Vec<_> = self.get_direct_dependents(remove).collect();
            let dependencies: Vec<_> = self.get_direct_dependencies(remove).collect();

            let removed_storage_entry = self.graph.remove_node(remove).expect(
                "The node should be present in the graph \
                    since we iterate over it using bfs",
            );
            self.clear_cache(&removed_storage_entry);

            for dependent in dependents {
                queue.push_back(dependent);

                #[cfg(test)]
                if !nodes_in_queue.insert(dependent) {
                    panic!(
                        "The node is already in the queue for removal. The graph has a cycle."
                    );
                }
            }

            for dependency in dependencies {
                self.reduce_dependencies_cumulative_gas_tip_and_chain_count(
                    dependency,
                    &removed_storage_entry,
                );
            }
            result.push(removed_storage_entry);
        }

        result
    }

    /// Check if the input has the right data to spend the output present in pool.
    fn check_if_coin_input_can_spend_output(
        output: &Output,
        input: &Input,
    ) -> Result<(), Error> {
        if let Input::CoinSigned(CoinSigned {
            owner,
            amount,
            asset_id,
            ..
        })
        | Input::CoinPredicate(CoinPredicate {
            owner,
            amount,
            asset_id,
            ..
        }) = input
        {
            let i_owner = owner;
            let i_amount = amount;
            let i_asset_id = asset_id;
            match output {
                Output::Coin {
                    to,
                    amount,
                    asset_id,
                } => {
                    if to != i_owner {
                        return Err(Error::InputValidation(
                            InputValidationError::NotInsertedIoWrongOwner,
                        ))
                    }
                    if amount != i_amount {
                        return Err(Error::InputValidation(
                            InputValidationError::NotInsertedIoWrongAmount,
                        ))
                    }
                    if asset_id != i_asset_id {
                        return Err(Error::InputValidation(
                            InputValidationError::NotInsertedIoWrongAssetId,
                        ))
                    }
                }
                Output::Contract(_) => {
                    return Err(Error::InputValidation(
                        InputValidationError::NotInsertedIoContractOutput,
                    ))
                }
                Output::Change { .. } => {
                    return Err(Error::InputValidation(
                        InputValidationError::NotInsertedInputDependentOnChangeOrVariable,
                    ))
                }
                Output::Variable { .. } => {
                    return Err(Error::InputValidation(
                        InputValidationError::NotInsertedInputDependentOnChangeOrVariable,
                    ))
                }
                Output::ContractCreated { .. } => {
                    return Err(Error::InputValidation(
                        InputValidationError::NotInsertedIoContractOutput,
                    ))
                }
            };
        }
        Ok(())
    }

    /// Cache the transaction information in the storage caches.
    /// This is used to speed up the verification/dependencies searches of the transactions.
    fn cache_tx_infos(&mut self, tx_id: &TxId, node_id: NodeIndex) {
        let outputs = self
            .graph
            .node_weight(node_id)
            .expect(
                "The node should be present in the graph since we added it just before",
            )
            .transaction
            .outputs();

        for (index, output) in outputs.iter().enumerate() {
            // SAFETY: We deal with CheckedTransaction there which should already check this
            let index = u16::try_from(index).expect(
                "The number of outputs in a transaction should be less than `u16::max`",
            );
            let utxo_id = UtxoId::new(*tx_id, index);
            match output {
                Output::Coin { .. } => {
                    self.coins_creators.insert(utxo_id, node_id);
                }
                Output::ContractCreated { contract_id, .. } => {
                    self.contracts_creators.insert(*contract_id, node_id);
                }
                _ => {}
            }
        }
    }

    /// Clear the caches of the storage when a transaction is removed.
    fn clear_cache(&mut self, storage_entry: &StorageData) {
        let outputs = storage_entry.transaction.outputs();
        let tx_id = storage_entry.transaction.id();

        for (index, output) in outputs.iter().enumerate() {
            // SAFETY: We deal with CheckedTransaction there which should already check this
            let index = u16::try_from(index).expect(
                "The number of outputs in a transaction should be less than `u16::max`",
            );
            let utxo_id = UtxoId::new(tx_id, index);
            match output {
                Output::Coin { .. } => {
                    self.coins_creators.remove(&utxo_id);
                }
                Output::ContractCreated { contract_id, .. } => {
                    self.contracts_creators.remove(contract_id);
                }
                _ => {}
            }
        }
    }

    fn get_inner(&self, index: &NodeIndex) -> Option<&StorageData> {
        self.graph.node_weight(*index)
    }

    fn get_direct_dependents(
        &self,
        index: NodeIndex,
    ) -> impl Iterator<Item = NodeIndex> + '_ {
        self.graph
            .neighbors_directed(index, petgraph::Direction::Outgoing)
    }

    fn get_direct_dependencies(
        &self,
        index: NodeIndex,
    ) -> impl Iterator<Item = NodeIndex> + '_ {
        self.graph
            .neighbors_directed(index, petgraph::Direction::Incoming)
    }

    fn collect_transaction_direct_dependencies(
        &self,
        transaction: &PoolTransaction,
    ) -> Result<HashSet<NodeIndex>, Error> {
        let mut direct_dependencies = HashSet::new();
        for input in transaction.inputs() {
            match input {
                Input::CoinSigned(CoinSigned { utxo_id, .. })
                | Input::CoinPredicate(CoinPredicate { utxo_id, .. }) => {
                    if let Some(node_id) = self.coins_creators.get(utxo_id) {
                        direct_dependencies.insert(*node_id);

                        if direct_dependencies.len() >= self.config.max_txs_chain_count {
                            return Err(Error::Dependency(
                                DependencyError::NotInsertedChainDependencyTooBig,
                            ));
                        }
                    }
                }
                Input::MessageCoinSigned(MessageCoinSigned { .. })
                | Input::MessageCoinPredicate(MessageCoinPredicate { .. })
                | Input::MessageDataSigned(MessageDataSigned { .. })
                | Input::MessageDataPredicate(MessageDataPredicate { .. }) => {}
                Input::Contract(Contract { contract_id, .. }) => {
                    if let Some(node_id) = self.contracts_creators.get(contract_id) {
                        direct_dependencies.insert(*node_id);

                        if direct_dependencies.len() >= self.config.max_txs_chain_count {
                            return Err(Error::Dependency(
                                DependencyError::NotInsertedChainDependencyTooBig,
                            ));
                        }
                    }
                }
            }
        }
        Ok(direct_dependencies)
    }

    fn has_dependent(&self, index: NodeIndex) -> bool {
        self.get_direct_dependents(index).next().is_some()
    }

    #[cfg(test)]
    pub(crate) fn assert_integrity(
        &self,
        expected_txs: &[ArcPoolTx],
    ) -> Vec<(NodeIndex, bool)> {
        use std::ops::Deref;

        let mut txs_map: HashMap<TxId, ArcPoolTx> = expected_txs
            .iter()
            .map(|tx| (tx.id(), tx.clone()))
            .collect();
        let mut tx_id_node_id = HashMap::new();
        let mut txs_info = Vec::new();

        for node_id in self.graph.node_indices() {
            let node = self
                .graph
                .node_weight(node_id)
                .expect("A node not expected exists in storage");
            let has_dependencies = Storage::has_dependencies(self, &node_id);
            let tx_id = node.transaction.id();
            let tx = txs_map
                .remove(&tx_id)
                .expect("A transaction not expected exists in storage");
            assert_eq!(tx.deref(), node.transaction.deref());
            tx_id_node_id.insert(tx_id, node_id);
            txs_info.push((node_id, has_dependencies));
        }
        assert!(
            txs_map.is_empty(),
            "Some transactions are missing in storage {:?}",
            txs_map.keys()
        );

        let mut coins_creators = HashMap::new();
        let mut contracts_creators = HashMap::new();
        for expected_tx in expected_txs {
            for (i, output) in expected_tx.outputs().iter().enumerate() {
                match output {
                    Output::Coin { .. } => {
                        let utxo_id =
                            UtxoId::new(expected_tx.id(), i.try_into().unwrap());
                        coins_creators.insert(utxo_id, expected_tx.id());
                    }
                    Output::ContractCreated { contract_id, .. } => {
                        contracts_creators.insert(*contract_id, expected_tx.id());
                    }
                    Output::Contract(_)
                    | Output::Change { .. }
                    | Output::Variable { .. } => {}
                }
            }
        }
        for (utxo_id, node_id) in &self.coins_creators {
            let tx_id = coins_creators.remove(utxo_id).unwrap_or_else(|| panic!("A coin creator (coin: {}) is present in the storage that shouldn't be there", utxo_id));
            let expected_node_id = tx_id_node_id.get(&tx_id).unwrap_or_else(|| {
                panic!("A node id is missing for a transaction (tx_id: {})", tx_id)
            });
            assert_eq!(
                expected_node_id, node_id,
                "The node id is different from the expected one"
            );
        }
        assert!(
            coins_creators.is_empty(),
            "Some contract creators are missing in storage: {:?}",
            coins_creators
        );

        for (contract_id, node_id) in &self.contracts_creators {
            let tx_id = contracts_creators.remove(contract_id).unwrap_or_else(|| panic!("A contract creator (contract: {}) is present in the storage that shouldn't be there", contract_id));
            let expected_node_id = tx_id_node_id.get(&tx_id).unwrap_or_else(|| {
                panic!("A node id is missing for a transaction (tx_id: {})", tx_id)
            });
            assert_eq!(
                expected_node_id, node_id,
                "The node id is different from the expected one"
            );
        }
        assert!(
            contracts_creators.is_empty(),
            "Some contract creators are missing in storage: {:?}",
            contracts_creators
        );

        txs_info
    }
}

impl Storage for GraphStorage {
    type StorageIndex = NodeIndex;
    type CheckedTransaction = CheckedTransaction<Self::StorageIndex>;

    fn store_transaction(
        &mut self,
        checked_transaction: Self::CheckedTransaction,
        creation_instant: SystemTime,
    ) -> Self::StorageIndex {
        let (transaction, direct_dependencies, all_dependencies) =
            checked_transaction.unpack();
        let tx_id = transaction.id();

        // Add the new transaction to the graph and update the others in consequence
        let tip = transaction.tip();
        let gas = transaction.max_gas();
        let size = transaction.metered_bytes_size();

        // Update the cumulative tip and gas of the dependencies transactions and recursively their dependencies, etc.
        for node_id in all_dependencies {
            let Some(node) = self.graph.node_weight_mut(node_id) else {
                // We got all dependencies from the graph it shouldn't be possible
                debug_assert!(false, "Node with id {:?} not found", node_id);
                tracing::warn!("Node with id {:?} not found", node_id);
                continue
            };

            node.number_dependents_in_chain =
                node.number_dependents_in_chain.saturating_add(1);
            node.dependents_cumulative_tip =
                node.dependents_cumulative_tip.saturating_add(tip);
            node.dependents_cumulative_gas =
                node.dependents_cumulative_gas.saturating_add(gas);
            node.dependents_cumulative_bytes_size =
                node.dependents_cumulative_bytes_size.saturating_add(size);

            debug_assert!(node.dependents_cumulative_gas != 0);
            debug_assert!(node.number_dependents_in_chain != 0);
            debug_assert!(node.dependents_cumulative_bytes_size != 0);
        }

        let node = StorageData {
            dependents_cumulative_tip: tip,
            dependents_cumulative_gas: gas,
            dependents_cumulative_bytes_size: size,
            transaction,
            creation_instant,
            number_dependents_in_chain: 1,
        };

        // Add the transaction to the graph
        let node_id = self.graph.add_node(node);
        for dependency in direct_dependencies {
            debug_assert!(
                !self.graph.contains_edge(dependency, node_id),
                "Edge already exists"
            );
            self.graph.add_edge(dependency, node_id, ());
        }
        debug_assert!(!self.has_dependent(node_id));

        self.cache_tx_infos(&tx_id, node_id);

        node_id
    }

    fn can_store_transaction(
        &self,
        transaction: ArcPoolTx,
    ) -> Result<Self::CheckedTransaction, Error> {
        let direct_dependencies =
            self.collect_transaction_direct_dependencies(&transaction)?;

        let mut all_dependencies = HashSet::new();
        let mut to_check = direct_dependencies.iter().cloned().collect::<Vec<_>>();

        while let Some(node_id) = to_check.pop() {
            if all_dependencies.contains(&node_id) {
                // The graph heavy rely on the property of not having
                // diamond dependencies. An example of the diamond dependency:
                //
                // E - Executable transaction
                // D - Old dependent transaction
                // N - New dependent transaction
                //
                //      E
                //     / \
                //    D   D
                //     \ /
                //      N   <- Forbidden to insert
                //
                //
                // The non-diamond dependency example:
                //
                //   E   E       E       E
                //    \ /      / | \     |
                //     D      D  D  D    |
                //    / \    / \        / \
                //   D   D  D   D      D   D
                return Err(Error::Dependency(
                    DependencyError::DependentTransactionIsADiamondDeath,
                ));
            }

            all_dependencies.insert(node_id);

            if all_dependencies.len() >= self.config.max_txs_chain_count {
                return Err(Error::Dependency(
                    DependencyError::NotInsertedChainDependencyTooBig,
                ));
            }

            let Some(dependency_node) = self.graph.node_weight(node_id) else {
                // We got all dependencies from the graph it shouldn't be possible
                debug_assert!(false, "Node with id {:?} not found", node_id);
                tracing::warn!("Node with id {:?} not found", node_id);
                continue
            };

            if dependency_node.number_dependents_in_chain
                >= self.config.max_txs_chain_count
            {
                return Err(Error::Dependency(
                    DependencyError::NotInsertedChainDependencyTooBig,
                ));
            }

            if dependency_node.transaction.is_blob() {
                return Err(Error::Dependency(
                    DependencyError::NotInsertedDependentOnBlob,
                ));
            }

            to_check.extend(self.get_direct_dependencies(node_id));
        }

        Ok(CheckedTransaction::new(
            transaction,
            direct_dependencies,
            all_dependencies,
        ))
    }

    fn get(&self, index: &Self::StorageIndex) -> Option<&StorageData> {
        self.get_inner(index)
    }

    fn get_direct_dependents(
        &self,
        index: Self::StorageIndex,
    ) -> impl Iterator<Item = Self::StorageIndex> {
        self.get_direct_dependents(index)
    }

    fn has_dependencies(&self, index: &Self::StorageIndex) -> bool {
        self.get_direct_dependencies(*index).next().is_some()
    }

    fn validate_inputs(
        &self,
        transaction: &PoolTransaction,
        persistent_storage: &impl TxPoolPersistentStorage,
        extracted_outputs: &ExtractedOutputs,
        spent_inputs: &SpentInputs,
        utxo_validation: bool,
    ) -> Result<(), InputValidationErrorType> {
        let mut missing_inputs = Vec::new();
        for input in transaction.inputs() {
            match input {
                // If the utxo is created in the pool, need to check if we don't spend too much (utxo can still be unresolved)
                // If the utxo_validation is active, we need to check if the utxo exists in the database and is valid
                Input::CoinSigned(CoinSigned {
                    utxo_id,
                    owner,
                    amount,
                    asset_id,
                    ..
                })
                | Input::CoinPredicate(CoinPredicate {
                    utxo_id,
                    owner,
                    amount,
                    asset_id,
                    ..
                }) => {
                    if let Some(node_id) = self.coins_creators.get(utxo_id) {
                        let Some(node) = self.graph.node_weight(*node_id) else {
                            return Err(InputValidationErrorType::Inconsistency(
                                Error::Storage(format!(
                                    "Node with id {:?} not found",
                                    node_id
                                )),
                            ));
                        };
                        let output =
                            &node.transaction.outputs()[utxo_id.output_index() as usize];
                        if let Err(e) =
                            Self::check_if_coin_input_can_spend_output(output, input)
                        {
                            return Err(InputValidationErrorType::Inconsistency(e));
                        };
                    } else if utxo_validation {
                        if spent_inputs.is_spent_utxo(utxo_id) {
                            return Err(InputValidationErrorType::Inconsistency(
                                Error::UtxoInputWasAlreadySpent(*utxo_id),
                            ));
                        }

                        match persistent_storage.utxo(utxo_id) {
                            Ok(Some(coin)) => {
                                if !coin
                                    .matches_input(input)
                                    .expect("The input is coin above")
                                {
                                    return Err(InputValidationErrorType::Inconsistency(Error::InputValidation(
                                        InputValidationError::NotInsertedIoCoinMismatch,
                                    )));
                                }
                            }
                            Ok(None) => {
                                if extracted_outputs
                                    .coin_exists(utxo_id, owner, amount, asset_id)
                                {
                                    continue
                                }
                                missing_inputs.push(MissingInput::Utxo(*utxo_id));
                                continue
                            }
                            Err(e) => {
                                return Err(InputValidationErrorType::Inconsistency(
                                    Error::Database(format!("{:?}", e)),
                                ));
                            }
                        };
                    }
                }
                Input::MessageCoinSigned(MessageCoinSigned { nonce, .. })
                | Input::MessageCoinPredicate(MessageCoinPredicate { nonce, .. })
                | Input::MessageDataSigned(MessageDataSigned { nonce, .. })
                | Input::MessageDataPredicate(MessageDataPredicate { nonce, .. }) => {
                    // since message id is derived, we don't need to double check all the fields
                    // Maybe this should be on an other function as it's not a dependency finder but just a test
                    if utxo_validation {
                        if spent_inputs.is_spent_message(nonce) {
                            return Err(InputValidationErrorType::Inconsistency(
                                Error::MessageInputWasAlreadySpent(*nonce),
                            ));
                        }

                        match persistent_storage.message(nonce) {
                            Ok(Some(db_message)) => {
                                // verify message id integrity
                                if !db_message
                                    .matches_input(input)
                                    .expect("Input is a message above")
                                {
                                    return Err(InputValidationErrorType::Inconsistency(Error::InputValidation(
                                InputValidationError::NotInsertedIoMessageMismatch,
                            )));
                                }
                            }
                            Ok(None) => {
                                // For now we are not managing the case where the message is not found
                                // as a missing input.
                                return Err(InputValidationErrorType::Inconsistency(Error::InputValidation(
                                    InputValidationError::NotInsertedInputMessageUnknown(*nonce),
                                )));
                            }
                            Err(e) => {
                                return Err(InputValidationErrorType::Inconsistency(
                                    Error::Database(format!("{:?}", e)),
                                ));
                            }
                        };
                    }
                }
                Input::Contract(Contract { contract_id, .. }) => {
                    if !self.contracts_creators.contains_key(contract_id) {
                        match persistent_storage.contract_exist(contract_id) {
                            Ok(true) => {}
                            Ok(false) => {
                                if extracted_outputs.contract_exists(contract_id) {
                                    continue
                                }
                                missing_inputs.push(MissingInput::Contract(*contract_id));
                                continue
                            }
                            Err(e) => {
                                return Err(InputValidationErrorType::Inconsistency(
                                    Error::Database(format!("{:?}", e)),
                                ));
                            }
                        };
                    }
                }
            }
        }
        if missing_inputs.is_empty() {
            Ok(())
        } else {
            Err(InputValidationErrorType::MissingInputs(missing_inputs))
        }
    }

    fn remove_transaction_and_dependents_subtree(
        &mut self,
        index: Self::StorageIndex,
    ) -> RemovedTransactions {
        self.remove_node_and_dependent_sub_graph(index)
    }

    fn remove_transaction(&mut self, index: Self::StorageIndex) -> Option<StorageData> {
        self.graph.remove_node(index).inspect(|storage_entry| {
            self.clear_cache(storage_entry);
        })
    }
}

impl RatioTipGasSelectionAlgorithmStorage for GraphStorage {
    type StorageIndex = NodeIndex;

    fn get(&self, index: &Self::StorageIndex) -> Option<&StorageData> {
        self.get_inner(index)
    }

    fn get_dependents(
        &self,
        index: &Self::StorageIndex,
    ) -> impl Iterator<Item = Self::StorageIndex> {
        self.get_direct_dependents(*index)
    }

    fn has_dependencies(&self, index: &Self::StorageIndex) -> bool {
        self.get_direct_dependencies(*index).next().is_some()
    }

    fn remove(&mut self, index: &Self::StorageIndex) -> Option<StorageData> {
        self.graph.remove_node(*index).inspect(|storage_entry| {
            self.clear_cache(storage_entry);
        })
    }
}

#[allow(clippy::arithmetic_side_effects)]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::{
        StorageData,
        graph::GraphStorage,
    };
    use std::ops::Add;

    #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
    struct Resources {
        gas: u64,
        tip: u64,
        bytes: usize,
        number: usize,
    }

    impl From<&StorageData> for Resources {
        fn from(storage_data: &StorageData) -> Self {
            Self {
                gas: storage_data.dependents_cumulative_gas,
                tip: storage_data.dependents_cumulative_tip,
                bytes: storage_data.dependents_cumulative_bytes_size,
                number: storage_data.number_dependents_in_chain,
            }
        }
    }

    impl Add for Resources {
        type Output = Self;

        fn add(self, other: Self) -> Self {
            Self {
                gas: self.gas + other.gas,
                tip: self.tip + other.tip,
                bytes: self.bytes + other.bytes,
                number: self.number + other.number,
            }
        }
    }

    impl GraphStorage {
        pub fn check_integrity(&self) {
            let source_nodes = self
                .graph
                .externals(petgraph::Direction::Incoming)
                .collect::<Vec<_>>();
            let mut visited = HashMap::new();

            for source_node in source_nodes {
                self.integrity_recursions(source_node, &mut visited);
            }
        }

        fn integrity_recursions(
            &self,
            root: NodeIndex,
            visited: &mut HashMap<NodeIndex, HashSet<NodeIndex>>,
        ) -> HashSet<NodeIndex> {
            if let Some(sub_set) = visited.get(&root) {
                return sub_set.clone()
            }

            let root_data = self.graph.node_weight(root).unwrap();
            let actual_resources = Resources::from(root_data);
            let mut expected_resources = Resources::default();

            let mut subset = HashSet::new();
            subset.insert(root);

            for dependent in self.get_direct_dependents(root) {
                let dependent_subset = self.integrity_recursions(dependent, visited);
                subset.extend(dependent_subset);
            }

            for dependent in &subset {
                let dependent_data = self.graph.node_weight(*dependent).unwrap();
                let dependent_resources = Resources {
                    gas: dependent_data.transaction.max_gas(),
                    tip: dependent_data.transaction.tip(),
                    bytes: dependent_data.transaction.metered_bytes_size(),
                    number: 1,
                };
                expected_resources = expected_resources + dependent_resources;
            }

            visited.insert(root, subset.clone());

            if expected_resources != actual_resources {
                panic!(
                    "Expected: {:?}, Actual: {:?}, Graph: {:?}",
                    expected_resources, actual_resources, self.graph
                );
            }

            subset
        }
    }
}