fuel_core/
coins_query.rs

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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
use crate::{
    fuel_core_graphql_api::{
        database::ReadView,
        storage::coins::CoinsToSpendIndexKey,
    },
    graphql_api::ports::CoinsToSpendIndexIter,
    query::asset_query::{
        AssetQuery,
        AssetSpendTarget,
        Exclude,
    },
};
use core::mem::swap;
use fuel_core_services::yield_stream::StreamYieldExt;
use fuel_core_storage::{
    Error as StorageError,
    Result as StorageResult,
};
use fuel_core_types::{
    entities::coins::{
        CoinId,
        CoinType,
    },
    fuel_tx::UtxoId,
    fuel_types::{
        Address,
        AssetId,
        Nonce,
        Word,
    },
};
use futures::{
    Stream,
    StreamExt,
    TryStreamExt,
};
use rand::prelude::*;
use std::{
    cmp::Reverse,
    collections::HashSet,
};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum CoinsQueryError {
    #[error("store error occurred: {0}")]
    StorageError(StorageError),
    #[error("the target cannot be met due to no coins available or exceeding the {max} coin limit.")]
    InsufficientCoinsForTheMax {
        asset_id: AssetId,
        collected_amount: Word,
        max: u16,
    },
    #[error("the query contains duplicate assets")]
    DuplicateAssets(AssetId),
    #[error(
        "too many excluded ids: provided ({provided}) is > than allowed ({allowed})"
    )]
    TooManyExcludedId { provided: usize, allowed: u16 },
    #[error("the query requires more coins than the max allowed coins: required ({required}) > max ({max})")]
    TooManyCoinsSelected { required: usize, max: u16 },
    #[error("coins to spend index entry contains wrong coin foreign key")]
    IncorrectCoinForeignKeyInIndex,
    #[error("coins to spend index entry contains wrong message foreign key")]
    IncorrectMessageForeignKeyInIndex,
    #[error("error while processing the query: {0}")]
    UnexpectedInternalState(&'static str),
    #[error("coins to spend index contains incorrect key")]
    IncorrectCoinsToSpendIndexKey,
}

#[cfg(test)]
impl PartialEq for CoinsQueryError {
    fn eq(&self, other: &Self) -> bool {
        format!("{self:?}") == format!("{other:?}")
    }
}

pub struct ExcludedCoinIds<'a> {
    coins: HashSet<&'a UtxoId>,
    messages: HashSet<&'a Nonce>,
}

impl<'a> ExcludedCoinIds<'a> {
    pub(crate) fn new(
        coins: impl Iterator<Item = &'a UtxoId>,
        messages: impl Iterator<Item = &'a Nonce>,
    ) -> Self {
        Self {
            coins: coins.collect(),
            messages: messages.collect(),
        }
    }

    pub(crate) fn is_coin_excluded(&self, coin: &UtxoId) -> bool {
        self.coins.contains(&coin)
    }

    pub(crate) fn is_message_excluded(&self, message: &Nonce) -> bool {
        self.messages.contains(&message)
    }
}

/// The prepared spend queries.
pub struct SpendQuery {
    owner: Address,
    query_per_asset: Vec<AssetSpendTarget>,
    exclude: Exclude,
    base_asset_id: AssetId,
}

impl SpendQuery {
    // TODO: Check that number of `queries` is not too high(to prevent attacks).
    //  https://github.com/FuelLabs/fuel-core/issues/588#issuecomment-1240074551
    pub fn new(
        owner: Address,
        query_per_asset: &[AssetSpendTarget],
        exclude_vec: Option<Vec<CoinId>>,
        base_asset_id: AssetId,
    ) -> Result<Self, CoinsQueryError> {
        let exclude = exclude_vec.map_or_else(Default::default, Exclude::new);

        Ok(Self {
            owner,
            query_per_asset: query_per_asset.to_vec(),
            exclude,
            base_asset_id,
        })
    }

    /// Return `Asset`s.
    pub fn assets(&self) -> &Vec<AssetSpendTarget> {
        &self.query_per_asset
    }

    /// Return [`AssetQuery`]s.
    pub fn asset_queries<'a>(&'a self, db: &'a ReadView) -> Vec<AssetQuery<'a>> {
        self.query_per_asset
            .iter()
            .map(|asset| {
                AssetQuery::new(
                    &self.owner,
                    asset,
                    &self.base_asset_id,
                    Some(&self.exclude),
                    db,
                )
            })
            .collect()
    }

    /// Returns exclude that contains information about excluded ids.
    pub fn exclude(&self) -> &Exclude {
        &self.exclude
    }

    /// Returns the owner of the query.
    pub fn owner(&self) -> &Address {
        &self.owner
    }
}

/// Returns the biggest inputs of the `owner` to satisfy the required `target` of the asset. The
/// number of inputs for each asset can't exceed `max_inputs`, otherwise throw an error that query
/// can't be satisfied.
pub async fn largest_first(
    query: AssetQuery<'_>,
) -> Result<Vec<CoinType>, CoinsQueryError> {
    let target = query.asset.target;
    let max = query.asset.max;
    let asset_id = query.asset.id;
    let mut inputs: Vec<CoinType> = query.coins().try_collect().await?;
    inputs.sort_by_key(|coin| Reverse(coin.amount()));

    let mut collected_amount = 0u64;
    let mut coins = vec![];

    for coin in inputs {
        // Break if we don't need any more coins
        if collected_amount >= target {
            break
        }

        // Error if we can't fit more coins
        if coins.len() >= max as usize {
            return Err(CoinsQueryError::InsufficientCoinsForTheMax {
                asset_id,
                collected_amount,
                max,
            })
        }

        // Add to list
        collected_amount = collected_amount.saturating_add(coin.amount());
        coins.push(coin);
    }

    if collected_amount < target {
        return Err(CoinsQueryError::InsufficientCoinsForTheMax {
            asset_id,
            collected_amount,
            max,
        })
    }

    Ok(coins)
}

// An implementation of the method described on: https://iohk.io/en/blog/posts/2018/07/03/self-organisation-in-coin-selection/
pub async fn random_improve(
    db: &ReadView,
    spend_query: &SpendQuery,
) -> Result<Vec<Vec<CoinType>>, CoinsQueryError> {
    let mut coins_per_asset = vec![];

    for query in spend_query.asset_queries(db) {
        let target = query.asset.target;
        let max = query.asset.max;

        let mut inputs: Vec<_> = query.clone().coins().try_collect().await?;
        inputs.shuffle(&mut thread_rng());
        inputs.truncate(max as usize);

        let mut collected_amount = 0;
        let mut coins = vec![];

        // Set parameters according to spec
        let upper_target = target.saturating_mul(2);

        for coin in inputs {
            // Try to improve the result by adding dust to the result.
            if collected_amount >= target {
                // Break if found coin exceeds max `u64` or the upper limit
                if collected_amount == u64::MAX || coin.amount() > upper_target {
                    break
                }

                // Break if adding doesn't improve the distance
                let change_amount = collected_amount
                    .checked_sub(target)
                    .expect("We checked it above");
                let distance = target.abs_diff(change_amount);
                let next_distance =
                    target.abs_diff(change_amount.saturating_add(coin.amount()));
                if next_distance >= distance {
                    break
                }
            }

            // Add to list
            collected_amount = collected_amount.saturating_add(coin.amount());
            coins.push(coin);
        }

        // Fallback to largest_first if we can't fit more coins
        if collected_amount < target {
            swap(&mut coins, &mut largest_first(query).await?);
        }

        coins_per_asset.push(coins);
    }

    Ok(coins_per_asset)
}

pub async fn select_coins_to_spend(
    CoinsToSpendIndexIter {
        big_coins_iter,
        dust_coins_iter,
    }: CoinsToSpendIndexIter<'_>,
    total: u64,
    max: u16,
    asset_id: &AssetId,
    excluded_ids: &ExcludedCoinIds<'_>,
    batch_size: usize,
) -> Result<Vec<CoinsToSpendIndexKey>, CoinsQueryError> {
    // We aim to reduce dust creation by targeting twice the required amount for selection,
    // inspired by the random-improve approach. This increases the likelihood of generating
    // useful change outputs for future transactions, minimizing unusable dust outputs.
    // See also "let upper_target = target.saturating_mul(2);" in "fn random_improve()".
    const TOTAL_AMOUNT_ADJUSTMENT_FACTOR: u64 = 2;

    // After selecting large coins that cover at least twice the required amount,
    // we include a limited number of small (dust) coins. The maximum number of dust coins
    // is determined by the multiplier defined below. Specifically, the number of dust coins
    // will never exceed FACTOR times the number of large coins selected.
    //
    // This limit prevents excessive dust coins from being included in cases where
    // the query lacks a specified maximum limit (defaulting to 255).
    //
    // Example:
    // - If 3 large coins are selected (and FACTOR is 5), up to 15 dust coins may be included (0..=15).
    // - Still, if the selected dust can cover the amount of some big coins, the
    //   latter will be removed from the set
    const DUST_TO_BIG_COINS_FACTOR: u16 = 5;

    if total == 0 || max == 0 {
        return Ok(vec![])
    }

    let adjusted_total = total.saturating_mul(TOTAL_AMOUNT_ADJUSTMENT_FACTOR);

    let big_coins_stream = futures::stream::iter(big_coins_iter).yield_each(batch_size);
    let dust_coins_stream = futures::stream::iter(dust_coins_iter).yield_each(batch_size);

    let (selected_big_coins_total, selected_big_coins) =
        big_coins(big_coins_stream, adjusted_total, max, excluded_ids).await?;

    if selected_big_coins_total < total {
        return Err(CoinsQueryError::InsufficientCoinsForTheMax {
            asset_id: *asset_id,
            collected_amount: selected_big_coins_total,
            max,
        });
    }

    let Some(last_selected_big_coin) = selected_big_coins.last() else {
        // Should never happen, because at this stage we know that:
        // 1) selected_big_coins_total >= total
        // 2) total > 0
        // hence: selected_big_coins_total > 0
        // therefore, at least one coin is selected - if not, it's a bug
        return Err(CoinsQueryError::UnexpectedInternalState(
            "at least one coin should be selected",
        ));
    };

    let selected_big_coins_len = selected_big_coins.len();
    let number_of_big_coins: u16 = selected_big_coins_len.try_into().map_err(|_| {
        CoinsQueryError::TooManyCoinsSelected {
            required: selected_big_coins_len,
            max: u16::MAX,
        }
    })?;

    let max_dust_count =
        max_dust_count(max, number_of_big_coins, DUST_TO_BIG_COINS_FACTOR);
    let (dust_coins_total, selected_dust_coins) = dust_coins(
        dust_coins_stream,
        last_selected_big_coin,
        max_dust_count,
        excluded_ids,
    )
    .await?;

    let retained_big_coins_iter =
        skip_big_coins_up_to_amount(selected_big_coins, dust_coins_total);

    Ok((retained_big_coins_iter
        .map(Into::into)
        .chain(selected_dust_coins))
    .collect())
}

async fn big_coins(
    big_coins_stream: impl Stream<Item = StorageResult<CoinsToSpendIndexKey>> + Unpin,
    total: u64,
    max: u16,
    excluded_ids: &ExcludedCoinIds<'_>,
) -> Result<(u64, Vec<CoinsToSpendIndexKey>), CoinsQueryError> {
    select_coins_until(big_coins_stream, max, excluded_ids, |_, total_so_far| {
        total_so_far >= total
    })
    .await
}

async fn dust_coins(
    dust_coins_stream: impl Stream<Item = StorageResult<CoinsToSpendIndexKey>> + Unpin,
    last_big_coin: &CoinsToSpendIndexKey,
    max_dust_count: u16,
    excluded_ids: &ExcludedCoinIds<'_>,
) -> Result<(u64, Vec<CoinsToSpendIndexKey>), CoinsQueryError> {
    select_coins_until(
        dust_coins_stream,
        max_dust_count,
        excluded_ids,
        |coin, _| coin == last_big_coin,
    )
    .await
}

async fn select_coins_until<Pred>(
    mut coins_stream: impl Stream<Item = StorageResult<CoinsToSpendIndexKey>> + Unpin,
    max: u16,
    excluded_ids: &ExcludedCoinIds<'_>,
    predicate: Pred,
) -> Result<(u64, Vec<CoinsToSpendIndexKey>), CoinsQueryError>
where
    Pred: Fn(&CoinsToSpendIndexKey, u64) -> bool,
{
    let mut coins_total_value: u64 = 0;
    let mut coins = Vec::with_capacity(max as usize);
    while let Some(coin) = coins_stream.next().await {
        let coin = coin?;
        if !is_excluded(&coin, excluded_ids) {
            if coins.len() >= max as usize || predicate(&coin, coins_total_value) {
                break;
            }
            let amount = coin.amount();
            coins_total_value = coins_total_value.saturating_add(amount);
            coins.push(coin);
        }
    }
    Ok((coins_total_value, coins))
}

fn is_excluded(key: &CoinsToSpendIndexKey, excluded_ids: &ExcludedCoinIds) -> bool {
    match key {
        CoinsToSpendIndexKey::Coin { utxo_id, .. } => {
            excluded_ids.is_coin_excluded(utxo_id)
        }
        CoinsToSpendIndexKey::Message { nonce, .. } => {
            excluded_ids.is_message_excluded(nonce)
        }
    }
}

fn max_dust_count(max: u16, big_coins_len: u16, dust_to_big_coins_factor: u16) -> u16 {
    let mut rng = rand::thread_rng();

    let max_from_factor = big_coins_len.saturating_mul(dust_to_big_coins_factor);
    let max_adjusted = max.saturating_sub(big_coins_len);
    let upper_bound = max_from_factor.min(max_adjusted);

    rng.gen_range(0..=upper_bound)
}

fn skip_big_coins_up_to_amount(
    big_coins: impl IntoIterator<Item = CoinsToSpendIndexKey>,
    skipped_amount: u64,
) -> impl Iterator<Item = CoinsToSpendIndexKey> {
    let mut current_dust_coins_value = skipped_amount;
    big_coins.into_iter().skip_while(move |item| {
        let item_amount = item.amount();
        current_dust_coins_value
            .checked_sub(item_amount)
            .map(|new_value| {
                current_dust_coins_value = new_value;
                true
            })
            .unwrap_or(false)
    })
}

impl From<StorageError> for CoinsQueryError {
    fn from(e: StorageError) -> Self {
        CoinsQueryError::StorageError(e)
    }
}

#[allow(clippy::arithmetic_side_effects)]
#[cfg(test)]
mod tests {
    use crate::{
        coins_query::{
            largest_first,
            max_dust_count,
            random_improve,
            CoinsQueryError,
            SpendQuery,
        },
        combined_database::CombinedDatabase,
        fuel_core_graphql_api::{
            api_service::ReadDatabase as ServiceDatabase,
            storage::{
                coins::{
                    owner_coin_id_key,
                    OwnedCoins,
                },
                messages::{
                    OwnedMessageIds,
                    OwnedMessageKey,
                },
            },
        },
        query::asset_query::{
            AssetQuery,
            AssetSpendTarget,
        },
    };
    use assert_matches::assert_matches;
    use fuel_core_storage::{
        iter::IterDirection,
        tables::{
            Coins,
            Messages,
        },
        StorageMutate,
    };
    use fuel_core_types::{
        blockchain::primitives::DaBlockHeight,
        entities::{
            coins::coin::{
                Coin,
                CompressedCoin,
            },
            relayer::message::{
                Message,
                MessageV1,
            },
        },
        fuel_asm::Word,
        fuel_tx::*,
    };
    use futures::TryStreamExt;
    use itertools::Itertools;
    use proptest::{
        prelude::*,
        proptest,
    };
    use rand::{
        rngs::StdRng,
        Rng,
        SeedableRng,
    };
    use std::cmp::Reverse;

    fn setup_coins() -> (Address, [AssetId; 2], AssetId, TestDatabase) {
        let mut rng = StdRng::seed_from_u64(0xf00df00d);
        let owner = Address::default();
        let asset_ids = [rng.gen(), rng.gen()];
        let base_asset_id = rng.gen();
        let mut db = TestDatabase::new();
        (0..5usize).for_each(|i| {
            db.make_coin(owner, (i + 1) as Word, asset_ids[0]);
            db.make_coin(owner, (i + 1) as Word, asset_ids[1]);
        });

        (owner, asset_ids, base_asset_id, db)
    }

    fn setup_messages() -> (Address, AssetId, TestDatabase) {
        let mut rng = StdRng::seed_from_u64(0xf00df00d);
        let owner = Address::default();
        let base_asset_id = rng.gen();
        let mut db = TestDatabase::new();
        (0..5usize).for_each(|i| {
            db.make_message(owner, (i + 1) as Word);
        });

        (owner, base_asset_id, db)
    }

    fn setup_coins_and_messages() -> (Address, [AssetId; 2], AssetId, TestDatabase) {
        let mut rng = StdRng::seed_from_u64(0xf00df00d);
        let owner = Address::default();
        let base_asset_id = rng.gen();
        let asset_ids = [base_asset_id, rng.gen()];
        let mut db = TestDatabase::new();
        // 2 coins and 3 messages
        (0..2usize).for_each(|i| {
            db.make_coin(owner, (i + 1) as Word, asset_ids[0]);
        });
        (2..5usize).for_each(|i| {
            db.make_message(owner, (i + 1) as Word);
        });

        (0..5usize).for_each(|i| {
            db.make_coin(owner, (i + 1) as Word, asset_ids[1]);
        });

        (owner, asset_ids, base_asset_id, db)
    }

    mod largest_first {
        use super::*;

        async fn query(
            spend_query: &[AssetSpendTarget],
            owner: &Address,
            base_asset_id: &AssetId,
            db: &ServiceDatabase,
        ) -> Result<Vec<Vec<(AssetId, Word)>>, CoinsQueryError> {
            let mut results = vec![];

            for asset in spend_query {
                let coins = largest_first(AssetQuery::new(
                    owner,
                    asset,
                    base_asset_id,
                    None,
                    &db.test_view(),
                ))
                .await
                .map(|coins| {
                    coins
                        .iter()
                        .map(|coin| (*coin.asset_id(base_asset_id), coin.amount()))
                        .collect()
                })?;
                results.push(coins);
            }

            Ok(results)
        }

        async fn single_asset_assert(
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: &AssetId,
            db: TestDatabase,
        ) {
            let asset_id = asset_ids[0];

            // Query some targets, including higher than the owner's balance
            for target in 0..20 {
                let coins = query(
                    &[AssetSpendTarget::new(asset_id, target, u16::MAX)],
                    &owner,
                    base_asset_id,
                    &db.service_database(),
                )
                .await;

                // Transform result for convenience
                let coins = coins.map(|coins| {
                    coins[0]
                        .iter()
                        .map(|(id, amount)| {
                            // Check the asset ID before we drop it
                            assert_eq!(id, &asset_id);

                            *amount
                        })
                        .collect::<Vec<u64>>()
                });

                match target {
                    // This should return nothing
                    0 => {
                        assert_matches!(coins, Ok(coins) if coins.is_empty())
                    }
                    // This range should return the largest coins
                    1..=5 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5])
                    }
                    // This range should return the largest two coins
                    6..=9 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5, 4])
                    }
                    // This range should return the largest three coins
                    10..=12 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5, 4, 3])
                    }
                    // This range should return the largest four coins
                    13..=14 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5, 4, 3, 2])
                    }
                    // This range should return all coins
                    15 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5, 4, 3, 2, 1])
                    }
                    // Asking for more than the owner's balance should error
                    _ => {
                        assert_matches!(
                            coins,
                            Err(CoinsQueryError::InsufficientCoinsForTheMax {
                                asset_id: _,
                                collected_amount: 15,
                                max: u16::MAX
                            })
                        )
                    }
                };
            }

            // Query with too small max_inputs
            let coins = query(
                &[AssetSpendTarget::new(asset_id, 6, 1)],
                &owner,
                base_asset_id,
                &db.service_database(),
            )
            .await;
            assert_matches!(
                coins,
                Err(CoinsQueryError::InsufficientCoinsForTheMax { .. })
            );
        }

        #[tokio::test]
        async fn single_asset_coins() {
            // Setup for coins
            let (owner, asset_ids, base_asset_id, db) = setup_coins();
            single_asset_assert(owner, &asset_ids, &base_asset_id, db).await;
        }

        #[tokio::test]
        async fn single_asset_messages() {
            // Setup for messages
            let (owner, base_asset_id, db) = setup_messages();
            single_asset_assert(owner, &[base_asset_id], &base_asset_id, db).await;
        }

        #[tokio::test]
        async fn single_asset_coins_and_messages() {
            // Setup for coins and messages
            let (owner, asset_ids, base_asset_id, db) = setup_coins_and_messages();
            single_asset_assert(owner, &asset_ids, &base_asset_id, db).await;
        }

        async fn multiple_assets_helper(
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: &AssetId,
            db: TestDatabase,
        ) {
            let coins = query(
                &[
                    AssetSpendTarget::new(asset_ids[0], 3, u16::MAX),
                    AssetSpendTarget::new(asset_ids[1], 6, u16::MAX),
                ],
                &owner,
                base_asset_id,
                &db.service_database(),
            )
            .await;
            let expected = vec![
                vec![(asset_ids[0], 5)],
                vec![(asset_ids[1], 5), (asset_ids[1], 4)],
            ];
            assert_matches!(coins, Ok(coins) if coins == expected);
        }

        #[tokio::test]
        async fn multiple_assets_coins() {
            // Setup coins
            let (owner, asset_ids, base_asset_id, db) = setup_coins();
            multiple_assets_helper(owner, &asset_ids, &base_asset_id, db).await;
        }

        #[tokio::test]
        async fn multiple_assets_coins_and_messages() {
            // Setup coins and messages
            let (owner, asset_ids, base_asset_id, db) = setup_coins_and_messages();
            multiple_assets_helper(owner, &asset_ids, &base_asset_id, db).await;
        }
    }

    mod random_improve {
        use super::*;

        async fn query(
            query_per_asset: Vec<AssetSpendTarget>,
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: AssetId,
            db: &ServiceDatabase,
        ) -> Result<Vec<(AssetId, u64)>, CoinsQueryError> {
            let coins = random_improve(
                &db.test_view(),
                &SpendQuery::new(owner, &query_per_asset, None, base_asset_id)?,
            )
            .await;

            // Transform result for convenience
            coins.map(|coins| {
                coins
                    .into_iter()
                    .flat_map(|coins| {
                        coins
                            .into_iter()
                            .map(|coin| (*coin.asset_id(&base_asset_id), coin.amount()))
                            .sorted_by_key(|(asset_id, amount)| {
                                (
                                    asset_ids.iter().position(|c| c == asset_id).unwrap(),
                                    Reverse(*amount),
                                )
                            })
                    })
                    .collect()
            })
        }

        async fn single_asset_assert(
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: AssetId,
            db: TestDatabase,
        ) {
            let asset_id = asset_ids[0];

            // Query some amounts, including higher than the owner's balance
            for amount in 0..20 {
                let coins = query(
                    vec![AssetSpendTarget::new(asset_id, amount, u16::MAX)],
                    owner,
                    asset_ids,
                    base_asset_id,
                    &db.service_database(),
                )
                .await;

                // Transform result for convenience
                let coins = coins.map(|coins| {
                    coins
                        .into_iter()
                        .map(|(id, amount)| {
                            // Check the asset ID before we drop it
                            assert_eq!(id, asset_id);

                            amount
                        })
                        .collect::<Vec<u64>>()
                });

                match amount {
                    // This should return nothing
                    0 => assert_matches!(coins, Ok(coins) if coins.is_empty()),
                    // This range should...
                    1..=7 => {
                        // ...satisfy the amount
                        assert_matches!(coins, Ok(coins) if coins.iter().sum::<u64>() >= amount)
                        // ...and add more for dust management
                        // TODO: Implement the test
                    }
                    // This range should return all coins
                    8..=15 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![5, 4, 3, 2, 1])
                    }
                    // Asking for more than the owner's balance should error
                    _ => {
                        assert_matches!(
                            coins,
                            Err(CoinsQueryError::InsufficientCoinsForTheMax {
                                asset_id: _,
                                collected_amount: 15,
                                max: u16::MAX
                            })
                        )
                    }
                };
            }

            // Query with too small max_inputs
            let coins = query(
                vec![AssetSpendTarget::new(
                    asset_id, 6, // target
                    1, // max
                )],
                owner,
                asset_ids,
                base_asset_id,
                &db.service_database(),
            )
            .await;
            assert_matches!(
                coins,
                Err(CoinsQueryError::InsufficientCoinsForTheMax { .. })
            );
        }

        #[tokio::test]
        async fn single_asset_coins() {
            // Setup for coins
            let (owner, asset_ids, base_asset_id, db) = setup_coins();
            single_asset_assert(owner, &asset_ids, base_asset_id, db).await;
        }

        #[tokio::test]
        async fn single_asset_messages() {
            // Setup for messages
            let (owner, base_asset_id, db) = setup_messages();
            single_asset_assert(owner, &[base_asset_id], base_asset_id, db).await;
        }

        #[tokio::test]
        async fn single_asset_coins_and_messages() {
            // Setup for coins and messages
            let (owner, asset_ids, base_asset_id, db) = setup_coins_and_messages();
            single_asset_assert(owner, &asset_ids, base_asset_id, db).await;
        }

        async fn multiple_assets_assert(
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: AssetId,
            db: TestDatabase,
        ) {
            // Query multiple asset IDs
            let coins = query(
                vec![
                    AssetSpendTarget::new(
                        asset_ids[0],
                        3, // target
                        3, // max
                    ),
                    AssetSpendTarget::new(
                        asset_ids[1],
                        6, // target
                        3, // max
                    ),
                ],
                owner,
                asset_ids,
                base_asset_id,
                &db.service_database(),
            )
            .await;
            assert_matches!(coins, Ok(ref coins) if coins.len() <= 6);
            let coins = coins.unwrap();
            assert!(
                coins
                    .iter()
                    .filter(|c| c.0 == asset_ids[0])
                    .map(|c| c.1)
                    .sum::<u64>()
                    >= 3
            );
            assert!(
                coins
                    .iter()
                    .filter(|c| c.0 == asset_ids[1])
                    .map(|c| c.1)
                    .sum::<u64>()
                    >= 6
            );
        }

        #[tokio::test]
        async fn multiple_assets_coins() {
            // Setup coins
            let (owner, asset_ids, base_asset_id, db) = setup_coins();
            multiple_assets_assert(owner, &asset_ids, base_asset_id, db).await;
        }

        #[tokio::test]
        async fn multiple_assets_coins_and_messages() {
            // Setup coins and messages
            let (owner, asset_ids, base_asset_id, db) = setup_coins_and_messages();
            multiple_assets_assert(owner, &asset_ids, base_asset_id, db).await;
        }
    }

    mod exclusion {
        use super::*;
        use fuel_core_types::entities::coins::CoinId;

        async fn query(
            db: &ServiceDatabase,
            owner: Address,
            base_asset_id: AssetId,
            asset_ids: &[AssetId],
            query_per_asset: Vec<AssetSpendTarget>,
            excluded_ids: Vec<CoinId>,
        ) -> Result<Vec<(AssetId, u64)>, CoinsQueryError> {
            let spend_query = SpendQuery::new(
                owner,
                &query_per_asset,
                Some(excluded_ids),
                base_asset_id,
            )?;
            let coins = random_improve(&db.test_view(), &spend_query).await;

            // Transform result for convenience
            coins.map(|coins| {
                coins
                    .into_iter()
                    .flat_map(|coin| {
                        coin.into_iter()
                            .map(|coin| (*coin.asset_id(&base_asset_id), coin.amount()))
                            .sorted_by_key(|(asset_id, amount)| {
                                (
                                    asset_ids.iter().position(|c| c == asset_id).unwrap(),
                                    Reverse(*amount),
                                )
                            })
                    })
                    .collect()
            })
        }

        async fn exclusion_assert(
            owner: Address,
            asset_ids: &[AssetId],
            base_asset_id: AssetId,
            db: TestDatabase,
            excluded_ids: Vec<CoinId>,
        ) {
            let asset_id = asset_ids[0];

            // Query some amounts, including higher than the owner's balance
            for amount in 0..20 {
                let coins = query(
                    &db.service_database(),
                    owner,
                    base_asset_id,
                    asset_ids,
                    vec![AssetSpendTarget::new(asset_id, amount, u16::MAX)],
                    excluded_ids.clone(),
                )
                .await;

                // Transform result for convenience
                let coins = coins.map(|coins| {
                    coins
                        .into_iter()
                        .map(|(id, amount)| {
                            // Check the asset ID before we drop it
                            assert_eq!(id, asset_id);
                            amount
                        })
                        .collect::<Vec<u64>>()
                });

                match amount {
                    // This should return nothing
                    0 => assert_matches!(coins, Ok(coins) if coins.is_empty()),
                    // This range should...
                    1..=4 => {
                        // ...satisfy the amount
                        assert_matches!(coins, Ok(coins) if coins.iter().sum::<u64>() >= amount)
                        // ...and add more for dust management
                        // TODO: Implement the test
                    }
                    // This range should return all coins
                    5..=10 => {
                        assert_matches!(coins, Ok(coins) if coins == vec![4, 3, 2, 1])
                    }
                    // Asking for more than the owner's balance should error
                    _ => {
                        assert_matches!(
                            coins,
                            Err(CoinsQueryError::InsufficientCoinsForTheMax {
                                asset_id: _,
                                collected_amount: 10,
                                max: u16::MAX
                            })
                        )
                    }
                };
            }
        }

        #[tokio::test]
        async fn exclusion_coins() {
            // Setup coins
            let (owner, asset_ids, base_asset_id, db) = setup_coins();

            // Exclude largest coin IDs
            let excluded_ids = db
                .owned_coins(&owner)
                .await
                .into_iter()
                .filter(|coin| coin.amount == 5)
                .map(|coin| CoinId::Utxo(coin.utxo_id))
                .collect_vec();

            exclusion_assert(owner, &asset_ids, base_asset_id, db, excluded_ids).await;
        }

        #[tokio::test]
        async fn exclusion_messages() {
            // Setup messages
            let (owner, base_asset_id, db) = setup_messages();

            // Exclude largest messages IDs
            let excluded_ids = db
                .owned_messages(&owner)
                .await
                .into_iter()
                .filter(|message| message.amount() == 5)
                .map(|message| CoinId::Message(*message.id()))
                .collect_vec();

            exclusion_assert(owner, &[base_asset_id], base_asset_id, db, excluded_ids)
                .await;
        }

        #[tokio::test]
        async fn exclusion_coins_and_messages() {
            // Setup coins and messages
            let (owner, asset_ids, base_asset_id, db) = setup_coins_and_messages();

            // Exclude largest messages IDs, because coins only 1 and 2
            let excluded_ids = db
                .owned_messages(&owner)
                .await
                .into_iter()
                .filter(|message| message.amount() == 5)
                .map(|message| CoinId::Message(*message.id()))
                .collect_vec();

            exclusion_assert(owner, &asset_ids, base_asset_id, db, excluded_ids).await;
        }
    }

    mod indexed_coins_to_spend {
        use fuel_core_storage::iter::IntoBoxedIter;
        use fuel_core_types::{
            entities::coins::coin::Coin,
            fuel_tx::{
                AssetId,
                TxId,
                UtxoId,
                Word,
            },
        };

        use crate::{
            coins_query::{
                select_coins_to_spend,
                select_coins_until,
                CoinsQueryError,
                CoinsToSpendIndexKey,
                ExcludedCoinIds,
            },
            graphql_api::ports::CoinsToSpendIndexIter,
        };

        const BATCH_SIZE: usize = 1;

        struct TestCoinSpec {
            index_entry: Result<CoinsToSpendIndexKey, fuel_core_storage::Error>,
            utxo_id: UtxoId,
        }

        fn setup_test_coins(coins: impl IntoIterator<Item = u8>) -> Vec<TestCoinSpec> {
            coins
                .into_iter()
                .map(|i| {
                    let tx_id: TxId = [i; 32].into();
                    let output_index = i as u16;
                    let utxo_id = UtxoId::new(tx_id, output_index);

                    let coin = Coin {
                        utxo_id,
                        owner: Default::default(),
                        amount: i as u64,
                        asset_id: Default::default(),
                        tx_pointer: Default::default(),
                    };

                    TestCoinSpec {
                        index_entry: Ok(CoinsToSpendIndexKey::from_coin(&coin)),
                        utxo_id,
                    }
                })
                .collect()
        }

        #[tokio::test]
        async fn select_coins_until_respects_max() {
            // Given
            const MAX: u16 = 3;

            let coins = setup_test_coins([1, 2, 3, 4, 5]);
            let (coins, _): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            // When
            let result = select_coins_until(
                futures::stream::iter(coins),
                MAX,
                &excluded,
                |_, _| false,
            )
            .await
            .expect("should select coins");

            // Then
            assert_eq!(result.0, 1 + 2 + 3); // Limit is set at 3 coins
            assert_eq!(result.1.len(), 3);
        }

        #[tokio::test]
        async fn select_coins_until_respects_excluded_ids() {
            // Given
            const MAX: u16 = u16::MAX;

            let coins = setup_test_coins([1, 2, 3, 4, 5]);
            let (coins, utxo_ids): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();

            // Exclude coin with amount '2'.
            let utxo_id = utxo_ids[1];
            let excluded =
                ExcludedCoinIds::new(std::iter::once(&utxo_id), std::iter::empty());

            // When
            let result = select_coins_until(
                futures::stream::iter(coins),
                MAX,
                &excluded,
                |_, _| false,
            )
            .await
            .expect("should select coins");

            // Then
            assert_eq!(result.0, 1 + 3 + 4 + 5); // '2' is skipped.
            assert_eq!(result.1.len(), 4);
        }

        #[tokio::test]
        async fn select_coins_until_respects_predicate() {
            // Given
            const MAX: u16 = u16::MAX;
            const TOTAL: u64 = 7;

            let coins = setup_test_coins([1, 2, 3, 4, 5]);
            let (coins, _): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            let predicate: fn(&CoinsToSpendIndexKey, u64) -> bool =
                |_, total| total > TOTAL;

            // When
            let result = select_coins_until(
                futures::stream::iter(coins),
                MAX,
                &excluded,
                predicate,
            )
            .await
            .expect("should select coins");

            // Then
            assert_eq!(result.0, 1 + 2 + 3 + 4); // Keep selecting until total is greater than 7.
            assert_eq!(result.1.len(), 4);
        }

        #[tokio::test]
        async fn already_selected_big_coins_are_never_reselected_as_dust() {
            // Given
            const MAX: u16 = u16::MAX;
            const TOTAL: u64 = 101;

            let test_coins = [100, 100, 4, 3, 2];
            let big_coins_iter = setup_test_coins(test_coins)
                .into_iter()
                .map(|spec| spec.index_entry)
                .into_boxed();

            let dust_coins_iter = setup_test_coins(test_coins)
                .into_iter()
                .rev()
                .map(|spec| spec.index_entry)
                .into_boxed();

            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter,
                dust_coins_iter,
            };

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            // When
            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &AssetId::default(),
                &excluded,
                BATCH_SIZE,
            )
            .await
            .expect("should not error");

            let mut results = result
                .into_iter()
                .map(|key| key.amount())
                .collect::<Vec<_>>();

            // Then

            // Because we select a total of 202 (TOTAL * 2), first 3 coins should always selected (100, 100, 4).
            let expected = vec![100, 100, 4];
            let actual: Vec<_> = results.drain(..3).collect();
            assert_eq!(expected, actual);

            // The number of dust coins is selected randomly, so we might have:
            // - 0 dust coins
            // - 1 dust coin [2]
            // - 2 dust coins [2, 3]
            // Even though in majority of cases we will have 2 dust coins selected (due to
            // MAX being huge), we can't guarantee that, hence we assert against all possible cases.
            // The important fact is that neither 100 nor 4 are selected as dust coins.
            let expected_1: Vec<u64> = vec![];
            let expected_2: Vec<u64> = vec![2];
            let expected_3: Vec<u64> = vec![2, 3];
            let actual: Vec<_> = results;

            assert!(
                actual == expected_1 || actual == expected_2 || actual == expected_3,
                "Unexpected dust coins: {:?}",
                actual,
            );
        }

        #[tokio::test]
        async fn selects_double_the_value_of_coins() {
            // Given
            const MAX: u16 = u16::MAX;
            const TOTAL: u64 = 10;

            let coins = setup_test_coins([10, 10, 9, 8, 7]);
            let (coins, _): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter: coins.into_iter().into_boxed(),
                dust_coins_iter: std::iter::empty().into_boxed(),
            };

            // When
            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &AssetId::default(),
                &excluded,
                BATCH_SIZE,
            )
            .await
            .expect("should not error");

            // Then
            let results: Vec<_> = result.into_iter().map(|key| key.amount()).collect();
            assert_eq!(results, vec![10, 10]);
        }

        #[tokio::test]
        async fn selection_algorithm_should_bail_on_storage_error() {
            // Given
            const MAX: u16 = u16::MAX;
            const TOTAL: u64 = 101;

            let coins = setup_test_coins([10, 9, 8, 7]);
            let (mut coins, _): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();
            let error = fuel_core_storage::Error::NotFound("S1", "S2");

            let first_2: Vec<_> = coins.drain(..2).collect();
            let last_2: Vec<_> = std::mem::take(&mut coins);

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            // Inject an error into the middle of coins.
            let coins: Vec<_> = first_2
                .into_iter()
                .take(2)
                .chain(std::iter::once(Err(error)))
                .chain(last_2)
                .collect();
            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter: coins.into_iter().into_boxed(),
                dust_coins_iter: std::iter::empty().into_boxed(),
            };

            // When
            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &AssetId::default(),
                &excluded,
                BATCH_SIZE,
            )
            .await;

            // Then
            assert!(matches!(result, Err(actual_error)
                if CoinsQueryError::StorageError(fuel_core_storage::Error::NotFound("S1", "S2")) == actual_error));
        }

        #[tokio::test]
        async fn selection_algorithm_should_bail_on_incorrect_max() {
            // Given
            const MAX: u16 = 0;
            const TOTAL: u64 = 101;

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter: std::iter::empty().into_boxed(),
                dust_coins_iter: std::iter::empty().into_boxed(),
            };

            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &AssetId::default(),
                &excluded,
                BATCH_SIZE,
            )
            .await;

            // Then
            assert_eq!(result, Ok(Vec::new()));
        }

        #[tokio::test]
        async fn selection_algorithm_should_bail_on_incorrect_total() {
            // Given
            const MAX: u16 = 101;
            const TOTAL: u64 = 0;

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter: std::iter::empty().into_boxed(),
                dust_coins_iter: std::iter::empty().into_boxed(),
            };

            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &AssetId::default(),
                &excluded,
                BATCH_SIZE,
            )
            .await;

            // Then
            assert_eq!(result, Ok(Vec::new()));
        }

        #[tokio::test]
        async fn selection_algorithm_should_bail_on_not_enough_coins() {
            // Given
            const MAX: u16 = 3;
            const TOTAL: u64 = 2137;

            let coins = setup_test_coins([10, 9, 8, 7]);
            let (coins, _): (Vec<_>, Vec<_>) = coins
                .into_iter()
                .map(|spec| (spec.index_entry, spec.utxo_id))
                .unzip();

            let excluded = ExcludedCoinIds::new(std::iter::empty(), std::iter::empty());

            let coins_to_spend_iter = CoinsToSpendIndexIter {
                big_coins_iter: coins.into_iter().into_boxed(),
                dust_coins_iter: std::iter::empty().into_boxed(),
            };

            let asset_id = AssetId::default();

            let result = select_coins_to_spend(
                coins_to_spend_iter,
                TOTAL,
                MAX,
                &asset_id,
                &excluded,
                BATCH_SIZE,
            )
            .await;

            const EXPECTED_COLLECTED_AMOUNT: Word = 10 + 9 + 8; // Because MAX == 3

            // Then
            assert!(matches!(result, Err(actual_error)
                if CoinsQueryError::InsufficientCoinsForTheMax { asset_id, collected_amount: EXPECTED_COLLECTED_AMOUNT, max: MAX } == actual_error));
        }
    }

    #[derive(Clone, Debug)]
    struct TestCase {
        db_amount: Vec<Word>,
        target_amount: u64,
        max_coins: u16,
    }

    pub enum CoinType {
        Coin,
        Message,
    }

    async fn test_case_run(
        case: TestCase,
        coin_type: CoinType,
        base_asset_id: AssetId,
    ) -> Result<usize, CoinsQueryError> {
        let TestCase {
            db_amount,
            target_amount,
            max_coins,
        } = case;
        let owner = Address::default();
        let asset_ids = [base_asset_id];
        let mut db = TestDatabase::new();
        for amount in db_amount {
            match coin_type {
                CoinType::Coin => {
                    let _ = db.make_coin(owner, amount, asset_ids[0]);
                }
                CoinType::Message => {
                    let _ = db.make_message(owner, amount);
                }
            };
        }

        let coins = random_improve(
            &db.service_database().test_view(),
            &SpendQuery::new(
                owner,
                &[AssetSpendTarget {
                    id: asset_ids[0],
                    target: target_amount,
                    max: max_coins,
                }],
                None,
                base_asset_id,
            )?,
        )
        .await?;

        assert_eq!(coins.len(), 1);
        Ok(coins[0].len())
    }

    #[tokio::test]
    async fn insufficient_coins_returns_error() {
        let test_case = TestCase {
            db_amount: vec![0],
            target_amount: u64::MAX,
            max_coins: u16::MAX,
        };
        let mut rng = StdRng::seed_from_u64(0xF00DF00D);
        let base_asset_id = rng.gen();
        let coin_result =
            test_case_run(test_case.clone(), CoinType::Coin, base_asset_id).await;
        let message_result =
            test_case_run(test_case, CoinType::Message, base_asset_id).await;
        assert_eq!(coin_result, message_result);
        assert_matches!(
            coin_result,
            Err(CoinsQueryError::InsufficientCoinsForTheMax {
                asset_id: _base_asset_id,
                collected_amount: 0,
                max: u16::MAX
            })
        )
    }

    proptest! {
        #[test]
        fn max_dust_count_respects_limits(
            max in 1u16..255,
            number_of_big_coins in 1u16..255,
            factor in 1u16..10,
        ) {
            // We're at the stage of the algorithm where we have already selected the big coins and
            // we're trying to select the dust coins.
            // So we're sure that the following assumptions hold:
            // 1. number_of_big_coins <= max - big coin selection algo is capped at 'max'.
            // 2. there must be at least one big coin selected, otherwise we'll break
            //    with the `InsufficientCoinsForTheMax` error earlier.
            prop_assume!(number_of_big_coins <= max && number_of_big_coins >= 1);

            let max_dust_count = max_dust_count(max, number_of_big_coins, factor);
            prop_assert!(number_of_big_coins + max_dust_count <= max);
            prop_assert!(max_dust_count <= number_of_big_coins.saturating_mul(factor));
        }
    }

    #[test_case::test_case(
        TestCase {
            db_amount: vec![u64::MAX, u64::MAX],
            target_amount: u64::MAX,
            max_coins: u16::MAX,
        }
        => Ok(1)
        ; "Enough coins in the DB to reach target(u64::MAX) by 1 coin"
    )]
    #[test_case::test_case(
        TestCase {
            db_amount: vec![2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, u64::MAX - 1],
            target_amount: u64::MAX,
            max_coins: 2,
        }
        => Ok(2)
        ; "Enough coins in the DB to reach target(u64::MAX) by 2 coins"
    )]
    #[tokio::test]
    async fn corner_cases(case: TestCase) -> Result<usize, CoinsQueryError> {
        let mut rng = StdRng::seed_from_u64(0xF00DF00D);
        let base_asset_id = rng.gen();
        let coin_result =
            test_case_run(case.clone(), CoinType::Coin, base_asset_id).await;
        let message_result = test_case_run(case, CoinType::Message, base_asset_id).await;
        assert_eq!(coin_result, message_result);
        coin_result
    }

    #[tokio::test]
    async fn enough_coins_in_the_db_to_reach_target_u64_max_but_limit_is_zero() {
        let mut rng = StdRng::seed_from_u64(0xF00DF00D);

        let case = TestCase {
            db_amount: vec![u64::MAX, u64::MAX],
            target_amount: u64::MAX,
            max_coins: 0,
        };

        let base_asset_id = rng.gen();
        let coin_result =
            test_case_run(case.clone(), CoinType::Coin, base_asset_id).await;
        let message_result = test_case_run(case, CoinType::Message, base_asset_id).await;
        assert_eq!(coin_result, message_result);
        assert!(matches!(
            coin_result,
            Err(CoinsQueryError::InsufficientCoinsForTheMax { .. })
        ));
    }

    // TODO: Should use any mock database instead of the `fuel_core::CombinedDatabase`.
    pub struct TestDatabase {
        database: CombinedDatabase,
        last_coin_index: u64,
        last_message_index: u64,
    }

    impl TestDatabase {
        fn new() -> Self {
            Self {
                database: Default::default(),
                last_coin_index: Default::default(),
                last_message_index: Default::default(),
            }
        }

        fn service_database(&self) -> ServiceDatabase {
            let on_chain = self.database.on_chain().clone();
            let off_chain = self.database.off_chain().clone();
            ServiceDatabase::new(100, 0u32.into(), on_chain, off_chain)
                .expect("should create service database")
        }
    }

    impl TestDatabase {
        pub fn make_coin(
            &mut self,
            owner: Address,
            amount: Word,
            asset_id: AssetId,
        ) -> Coin {
            let index = self.last_coin_index;
            self.last_coin_index += 1;

            let id = UtxoId::new(Bytes32::from([0u8; 32]), index.try_into().unwrap());
            let mut coin = CompressedCoin::default();
            coin.set_owner(owner);
            coin.set_amount(amount);
            coin.set_asset_id(asset_id);

            let db = self.database.on_chain_mut();
            StorageMutate::<Coins>::insert(db, &id, &coin).unwrap();
            let db = self.database.off_chain_mut();
            let coin_by_owner = owner_coin_id_key(&owner, &id);
            StorageMutate::<OwnedCoins>::insert(db, &coin_by_owner, &()).unwrap();

            coin.uncompress(id)
        }

        pub fn make_message(&mut self, owner: Address, amount: Word) -> Message {
            let nonce = self.last_message_index.into();
            self.last_message_index += 1;

            let message: Message = MessageV1 {
                sender: Default::default(),
                recipient: owner,
                nonce,
                amount,
                data: vec![],
                da_height: DaBlockHeight::from(1u64),
            }
            .into();

            let db = self.database.on_chain_mut();
            StorageMutate::<Messages>::insert(db, message.id(), &message).unwrap();
            let db = self.database.off_chain_mut();
            let owned_message_key = OwnedMessageKey::new(&owner, &nonce);
            StorageMutate::<OwnedMessageIds>::insert(db, &owned_message_key, &())
                .unwrap();

            message
        }

        pub async fn owned_coins(&self, owner: &Address) -> Vec<Coin> {
            let query = self.service_database();
            let query = query.test_view();
            query
                .owned_coins(owner, None, IterDirection::Forward)
                .try_collect()
                .await
                .unwrap()
        }

        pub async fn owned_messages(&self, owner: &Address) -> Vec<Message> {
            let query = self.service_database();
            let query = query.test_view();
            query
                .owned_messages(owner, None, IterDirection::Forward)
                .try_collect()
                .await
                .unwrap()
        }
    }
}