tx3_resolver/inputs/
searching.rs

1use std::collections::HashSet;
2
3use tx3_lang::{
4    backend::{UtxoPattern, UtxoStore},
5    AssetClass, UtxoRef,
6};
7
8use crate::inputs::CanonicalQuery;
9
10use super::Error;
11
12#[derive(Debug, Clone)]
13pub enum Subset {
14    NotSet,
15    All,
16    Specific(HashSet<UtxoRef>),
17}
18
19impl Subset {
20    fn count(&self) -> Option<usize> {
21        match self {
22            Self::NotSet => None,
23            Self::All => None,
24            Self::Specific(s) => Some(s.len()),
25        }
26    }
27
28    #[allow(dead_code)]
29    fn union(a: Self, b: Self) -> Self {
30        match (a, b) {
31            (Self::NotSet, x) => x,
32            (x, Self::NotSet) => x,
33            (Self::All, _) => Self::All,
34            (_, Self::All) => Self::All,
35            (Self::Specific(s1), Self::Specific(s2)) => {
36                Self::Specific(s1.union(&s2).cloned().collect())
37            }
38        }
39    }
40
41    fn intersection(a: Self, b: Self) -> Self {
42        match (a, b) {
43            (Self::NotSet, x) => x,
44            (x, Self::NotSet) => x,
45            (Self::All, x) => x,
46            (x, Self::All) => x,
47            (Self::Specific(s1), Self::Specific(s2)) => {
48                Self::Specific(s1.intersection(&s2).cloned().collect())
49            }
50        }
51    }
52
53    fn is_empty(&self) -> bool {
54        match self {
55            Self::NotSet => true,
56            Self::All => false,
57            Self::Specific(s) => s.is_empty(),
58        }
59    }
60}
61
62impl From<Subset> for HashSet<UtxoRef> {
63    fn from(value: Subset) -> Self {
64        match value {
65            Subset::Specific(s) => s,
66            Subset::NotSet => HashSet::new(),
67            Subset::All => HashSet::new(),
68        }
69    }
70}
71
72impl From<HashSet<UtxoRef>> for Subset {
73    fn from(value: HashSet<UtxoRef>) -> Self {
74        Self::Specific(value)
75    }
76}
77
78#[derive(Debug, Clone)]
79pub struct SearchSpace {
80    pub union: Subset,
81    pub intersection: Subset,
82    pub by_address_count: Option<usize>,
83    pub by_asset_class_count: Option<usize>,
84    pub by_ref_count: Option<usize>,
85}
86
87impl SearchSpace {
88    fn new() -> Self {
89        Self {
90            union: Subset::NotSet,
91            intersection: Subset::NotSet,
92            by_address_count: None,
93            by_asset_class_count: None,
94            by_ref_count: None,
95        }
96    }
97
98    fn is_constrained(&self) -> bool {
99        match &self.intersection {
100            Subset::NotSet => false,
101            Subset::All => false,
102            Subset::Specific(_) => true,
103        }
104    }
105
106    fn include_subset(&mut self, subset: Subset) {
107        self.union = Subset::union(self.union.clone(), subset.clone());
108        self.intersection = Subset::intersection(self.intersection.clone(), subset);
109    }
110
111    fn include_matches(&mut self, utxos: HashSet<UtxoRef>) {
112        let matches = Subset::Specific(utxos);
113        self.include_subset(matches);
114    }
115
116    fn include_address_matches(&mut self, subset: Subset) {
117        *self.by_address_count.get_or_insert(0) += subset.count().unwrap_or(0);
118        self.include_subset(subset);
119    }
120
121    fn include_asset_class_matches(&mut self, subset: Subset) {
122        *self.by_asset_class_count.get_or_insert(0) += subset.count().unwrap_or(0);
123        self.include_subset(subset);
124    }
125
126    fn add_ref_matches(&mut self, utxos: HashSet<UtxoRef>) {
127        *self.by_ref_count.get_or_insert(0) += utxos.len();
128        self.include_matches(utxos);
129    }
130
131    pub fn take(&self, take: Option<usize>) -> HashSet<UtxoRef> {
132        let Some(take) = take else {
133            // if there's no limit, return everything we have
134            return self.union.clone().into();
135        };
136
137        // if we have a specific limit, we need to pick the best options. The
138        // intersection are the best matches since they are the most specific, so we
139        // take from them first. If we don't have enough, we take the remaining from the
140        // union.
141
142        let best: HashSet<_> = self.intersection.clone().into();
143
144        if best.len() < take {
145            let others: HashSet<_> = self.union.clone().into();
146            let diff: HashSet<_> = others.difference(&best).cloned().collect();
147            let remaining: HashSet<_> = diff.into_iter().take(take - best.len()).collect();
148            best.union(&remaining).cloned().collect()
149        } else {
150            best
151        }
152    }
153}
154
155async fn narrow_by_asset_class<T: UtxoStore>(
156    store: &T,
157    parent: Subset,
158    class: &AssetClass,
159) -> Result<Subset, Error> {
160    // skip filtering lovelace since it's not an custom asset
161    if matches!(class, AssetClass::Naked) {
162        return Ok(parent);
163    }
164
165    let AssetClass::Defined(policy, name) = class else {
166        return Ok(parent);
167    };
168
169    let utxos = store
170        .narrow_refs(UtxoPattern::by_asset(policy, name))
171        .await?;
172
173    Ok(Subset::intersection(parent, Subset::Specific(utxos)))
174}
175
176pub async fn narrow_search_space<T: UtxoStore>(
177    store: &T,
178    criteria: &CanonicalQuery,
179) -> Result<SearchSpace, Error> {
180    let mut search_space = SearchSpace::new();
181
182    let parent_subset = if let Some(address) = &criteria.address {
183        let utxos = store.narrow_refs(UtxoPattern::by_address(address)).await?;
184        Subset::Specific(utxos)
185    } else {
186        Subset::All
187    };
188
189    search_space.include_address_matches(parent_subset.clone());
190
191    if let Some(assets) = &criteria.min_amount {
192        for (class, amount) in assets.iter() {
193            if *amount > 0 {
194                let subset = narrow_by_asset_class(store, parent_subset.clone(), class).await?;
195                search_space.include_asset_class_matches(subset);
196            }
197        }
198    }
199
200    if !criteria.refs.is_empty() {
201        search_space.add_ref_matches(criteria.refs.clone());
202    }
203
204    if !search_space.is_constrained() {
205        dbg!(&search_space);
206        return Err(Error::InputQueryTooBroad);
207    }
208
209    Ok(search_space)
210}
211
212#[cfg(test)]
213mod tests {
214    use std::collections::HashSet;
215
216    use super::*;
217
218    use crate::mock;
219
220    fn assets_for(asset: mock::KnownAsset, amount: i128) -> tx3_lang::CanonicalAssets {
221        tx3_lang::CanonicalAssets::from_asset(
222            Some(asset.policy().as_ref()),
223            Some(asset.name().as_ref()),
224            amount,
225        )
226    }
227
228    fn cq(
229        address: Option<&mock::KnownAddress>,
230        min_assets: Option<tx3_lang::CanonicalAssets>,
231        refs: HashSet<UtxoRef>,
232    ) -> CanonicalQuery {
233        CanonicalQuery {
234            address: address.map(|a| a.to_bytes()),
235            min_amount: min_assets,
236            refs,
237            support_many: true,
238            collateral: false,
239        }
240    }
241
242    fn prepare_store() -> mock::MockStore {
243        mock::seed_random_memory_store(
244            |_: &mock::FuzzTxoRef, x: &mock::KnownAddress, seq: u64| {
245                if seq % 2 == 0 {
246                    mock::utxo_with_random_asset(x, mock::KnownAsset::Hosky, 500..1000)
247                } else {
248                    mock::utxo_with_random_amount(x, 4_000_000..5_000_000)
249                }
250            },
251            2..3,
252        )
253    }
254
255    async fn assert_space_matches<T: tx3_lang::backend::UtxoStore>(
256        store: &T,
257        criteria: CanonicalQuery,
258        expected: HashSet<UtxoRef>,
259    ) {
260        let space = narrow_search_space(store, &criteria).await.unwrap();
261        let got = space.take(Some(expected.len()));
262        assert_eq!(got, expected);
263    }
264
265    #[pollster::test]
266    async fn test_address_only() {
267        let store = prepare_store();
268
269        let addr = mock::KnownAddress::Alice;
270        let expected = store.by_known_address(&addr).await;
271
272        let criteria = cq(Some(&addr), None, HashSet::new());
273        assert_space_matches(&store, criteria, expected).await;
274    }
275
276    #[pollster::test]
277    async fn test_asset_only() {
278        let store = prepare_store();
279
280        let asset = mock::KnownAsset::Hosky;
281        let expected = store.by_known_asset(&asset).await;
282
283        let min_assets = assets_for(asset, 1);
284        let criteria = cq(None, Some(min_assets), HashSet::new());
285        assert_space_matches(&store, criteria, expected).await;
286    }
287
288    #[pollster::test]
289    async fn test_refs_only() {
290        let store = prepare_store();
291
292        let alice = mock::KnownAddress::Alice;
293        let bob = mock::KnownAddress::Bob;
294
295        let alice_refs = store.by_known_address(&alice).await;
296        let bob_refs = store.by_known_address(&bob).await;
297
298        let pick_one = |set: &HashSet<UtxoRef>| set.iter().next().unwrap().clone();
299        let refs: HashSet<UtxoRef> =
300            HashSet::from_iter(vec![pick_one(&alice_refs), pick_one(&bob_refs)]);
301
302        let criteria = cq(None, None, refs.clone());
303        assert_space_matches(&store, criteria, refs).await;
304    }
305
306    #[pollster::test]
307    async fn test_address_and_asset_intersection() {
308        let store = prepare_store();
309
310        let addr = mock::KnownAddress::Alice;
311        let asset = mock::KnownAsset::Hosky;
312
313        let by_addr = store.by_known_address(&addr).await;
314        let by_asset = store.by_known_asset(&asset).await;
315
316        let expected_best: HashSet<_> = by_addr.intersection(&by_asset).cloned().collect();
317
318        let min_assets = assets_for(asset, 1);
319        let criteria = cq(Some(&addr), Some(min_assets), HashSet::new());
320        assert_space_matches(&store, criteria, expected_best).await;
321    }
322
323    #[pollster::test]
324    async fn test_address_and_refs_intersection() {
325        let store = prepare_store();
326
327        let alice = mock::KnownAddress::Alice;
328        let bob = mock::KnownAddress::Bob;
329
330        let alice_refs = store.by_known_address(&alice).await;
331        let bob_refs = store.by_known_address(&bob).await;
332
333        let pick_one = |set: &HashSet<UtxoRef>| set.iter().next().unwrap().clone();
334        let refs: HashSet<UtxoRef> =
335            HashSet::from_iter(vec![pick_one(&alice_refs), pick_one(&bob_refs)]);
336
337        let expected_best: HashSet<_> = alice_refs.intersection(&refs).cloned().collect();
338
339        let criteria = cq(Some(&alice), None, refs);
340        assert_space_matches(&store, criteria, expected_best).await;
341    }
342
343    #[pollster::test]
344    async fn test_asset_and_refs_intersection() {
345        let store = prepare_store();
346
347        let asset = mock::KnownAsset::Hosky;
348
349        let by_asset = store.by_known_asset(&asset).await;
350
351        // pick one ref that surely has the asset, and another arbitrary ref from
352        // someone else
353        let alice = mock::KnownAddress::Alice;
354        let bob = mock::KnownAddress::Bob;
355
356        let alice_any = store.by_known_address(&alice).await;
357        let bob_any = store.by_known_address(&bob).await;
358
359        let pick_one = |set: &HashSet<UtxoRef>| set.iter().next().unwrap().clone();
360        let one_with_asset = pick_one(&by_asset);
361        let other_ref = pick_one(&bob_any.union(&alice_any).cloned().collect());
362
363        let refs: HashSet<UtxoRef> = HashSet::from_iter(vec![one_with_asset.clone(), other_ref]);
364        let expected_best: HashSet<_> = by_asset.intersection(&refs).cloned().collect();
365
366        let min_assets = assets_for(asset, 1);
367        let criteria = cq(None, Some(min_assets), refs);
368        assert_space_matches(&store, criteria, expected_best).await;
369    }
370
371    #[pollster::test]
372    async fn test_address_asset_and_refs_intersection() {
373        let store = prepare_store();
374
375        let addr = mock::KnownAddress::Alice;
376        let asset = mock::KnownAsset::Hosky;
377
378        let by_addr = store.by_known_address(&addr).await;
379        let by_asset = store.by_known_asset(&asset).await;
380
381        let both: HashSet<_> = by_addr.intersection(&by_asset).cloned().collect();
382        assert!(!both.is_empty());
383
384        let one_ref = both.iter().next().unwrap().clone();
385        let mut refs = HashSet::new();
386        refs.insert(one_ref.clone());
387
388        // include a distractor ref that does not satisfy all dims
389        let bob = mock::KnownAddress::Bob;
390        let bob_refs = store
391            .narrow_refs(tx3_lang::backend::UtxoPattern::by_address(&bob.to_bytes()))
392            .await
393            .unwrap();
394        let distractor = bob_refs.iter().next().unwrap().clone();
395        refs.insert(distractor);
396
397        let expected_best: HashSet<_> = both.intersection(&refs).cloned().collect();
398
399        let min_assets = assets_for(asset, 1);
400        let criteria = cq(Some(&addr), Some(min_assets), refs);
401        assert_space_matches(&store, criteria, expected_best).await;
402    }
403}