Skip to main content

tx3_resolver/inputs/
narrow.rs

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