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
//! Helper types for spk-based blockchain clients.

use crate::{
    collections::BTreeMap, local_chain::CheckPoint, ConfirmationBlockTime, Indexed, TxGraph,
};
use alloc::boxed::Box;
use bitcoin::{OutPoint, Script, ScriptBuf, Txid};
use core::marker::PhantomData;

/// Data required to perform a spk-based blockchain client sync.
///
/// A client sync fetches relevant chain data for a known list of scripts, transaction ids and
/// outpoints. The sync process also updates the chain from the given [`CheckPoint`].
pub struct SyncRequest {
    /// A checkpoint for the current chain [`LocalChain::tip`].
    /// The sync process will return a new chain update that extends this tip.
    ///
    /// [`LocalChain::tip`]: crate::local_chain::LocalChain::tip
    pub chain_tip: CheckPoint,
    /// Transactions that spend from or to these indexed script pubkeys.
    pub spks: Box<dyn ExactSizeIterator<Item = ScriptBuf> + Send>,
    /// Transactions with these txids.
    pub txids: Box<dyn ExactSizeIterator<Item = Txid> + Send>,
    /// Transactions with these outpoints or spent from these outpoints.
    pub outpoints: Box<dyn ExactSizeIterator<Item = OutPoint> + Send>,
}

impl SyncRequest {
    /// Construct a new [`SyncRequest`] from a given `cp` tip.
    pub fn from_chain_tip(cp: CheckPoint) -> Self {
        Self {
            chain_tip: cp,
            spks: Box::new(core::iter::empty()),
            txids: Box::new(core::iter::empty()),
            outpoints: Box::new(core::iter::empty()),
        }
    }

    /// Set the [`Script`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn set_spks(
        mut self,
        spks: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = ScriptBuf> + Send + 'static>,
    ) -> Self {
        self.spks = Box::new(spks.into_iter());
        self
    }

    /// Set the [`Txid`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn set_txids(
        mut self,
        txids: impl IntoIterator<IntoIter = impl ExactSizeIterator<Item = Txid> + Send + 'static>,
    ) -> Self {
        self.txids = Box::new(txids.into_iter());
        self
    }

    /// Set the [`OutPoint`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn set_outpoints(
        mut self,
        outpoints: impl IntoIterator<
            IntoIter = impl ExactSizeIterator<Item = OutPoint> + Send + 'static,
        >,
    ) -> Self {
        self.outpoints = Box::new(outpoints.into_iter());
        self
    }

    /// Chain on additional [`Script`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn chain_spks(
        mut self,
        spks: impl IntoIterator<
            IntoIter = impl ExactSizeIterator<Item = ScriptBuf> + Send + 'static,
            Item = ScriptBuf,
        >,
    ) -> Self {
        self.spks = Box::new(ExactSizeChain::new(self.spks, spks.into_iter()));
        self
    }

    /// Chain on additional [`Txid`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn chain_txids(
        mut self,
        txids: impl IntoIterator<
            IntoIter = impl ExactSizeIterator<Item = Txid> + Send + 'static,
            Item = Txid,
        >,
    ) -> Self {
        self.txids = Box::new(ExactSizeChain::new(self.txids, txids.into_iter()));
        self
    }

    /// Chain on additional [`OutPoint`]s that will be synced against.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn chain_outpoints(
        mut self,
        outpoints: impl IntoIterator<
            IntoIter = impl ExactSizeIterator<Item = OutPoint> + Send + 'static,
            Item = OutPoint,
        >,
    ) -> Self {
        self.outpoints = Box::new(ExactSizeChain::new(self.outpoints, outpoints.into_iter()));
        self
    }

    /// Add a closure that will be called for [`Script`]s previously added to this request.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn inspect_spks(
        mut self,
        mut inspect: impl FnMut(&Script) + Send + Sync + 'static,
    ) -> Self {
        self.spks = Box::new(self.spks.inspect(move |spk| inspect(spk)));
        self
    }

    /// Add a closure that will be called for [`Txid`]s previously added to this request.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn inspect_txids(mut self, mut inspect: impl FnMut(&Txid) + Send + Sync + 'static) -> Self {
        self.txids = Box::new(self.txids.inspect(move |txid| inspect(txid)));
        self
    }

    /// Add a closure that will be called for [`OutPoint`]s previously added to this request.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn inspect_outpoints(
        mut self,
        mut inspect: impl FnMut(&OutPoint) + Send + Sync + 'static,
    ) -> Self {
        self.outpoints = Box::new(self.outpoints.inspect(move |op| inspect(op)));
        self
    }

    /// Populate the request with revealed script pubkeys from `index` with the given `spk_range`.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[cfg(feature = "miniscript")]
    #[must_use]
    pub fn populate_with_revealed_spks<K: Clone + Ord + core::fmt::Debug + Send + Sync>(
        self,
        index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
        spk_range: impl core::ops::RangeBounds<K>,
    ) -> Self {
        use alloc::borrow::ToOwned;
        use alloc::vec::Vec;
        self.chain_spks(
            index
                .revealed_spks(spk_range)
                .map(|(_, spk)| spk.to_owned())
                .collect::<Vec<_>>(),
        )
    }
}

/// Data returned from a spk-based blockchain client sync.
///
/// See also [`SyncRequest`].
pub struct SyncResult<A = ConfirmationBlockTime> {
    /// The update to apply to the receiving [`TxGraph`].
    pub graph_update: TxGraph<A>,
    /// The update to apply to the receiving [`LocalChain`](crate::local_chain::LocalChain).
    pub chain_update: CheckPoint,
}

/// Data required to perform a spk-based blockchain client full scan.
///
/// A client full scan iterates through all the scripts for the given keychains, fetching relevant
/// data until some stop gap number of scripts is found that have no data. This operation is
/// generally only used when importing or restoring previously used keychains in which the list of
/// used scripts is not known. The full scan process also updates the chain from the given [`CheckPoint`].
pub struct FullScanRequest<K> {
    /// A checkpoint for the current [`LocalChain::tip`].
    /// The full scan process will return a new chain update that extends this tip.
    ///
    /// [`LocalChain::tip`]: crate::local_chain::LocalChain::tip
    pub chain_tip: CheckPoint,
    /// Iterators of script pubkeys indexed by the keychain index.
    pub spks_by_keychain: BTreeMap<K, Box<dyn Iterator<Item = Indexed<ScriptBuf>> + Send>>,
}

impl<K: Ord + Clone> FullScanRequest<K> {
    /// Construct a new [`FullScanRequest`] from a given `chain_tip`.
    #[must_use]
    pub fn from_chain_tip(chain_tip: CheckPoint) -> Self {
        Self {
            chain_tip,
            spks_by_keychain: BTreeMap::new(),
        }
    }

    /// Construct a new [`FullScanRequest`] from a given `chain_tip` and `index`.
    ///
    /// Unbounded script pubkey iterators for each keychain (`K`) are extracted using
    /// [`KeychainTxOutIndex::all_unbounded_spk_iters`] and is used to populate the
    /// [`FullScanRequest`].
    ///
    /// [`KeychainTxOutIndex::all_unbounded_spk_iters`]: crate::indexer::keychain_txout::KeychainTxOutIndex::all_unbounded_spk_iters
    #[cfg(feature = "miniscript")]
    #[must_use]
    pub fn from_keychain_txout_index(
        chain_tip: CheckPoint,
        index: &crate::indexer::keychain_txout::KeychainTxOutIndex<K>,
    ) -> Self
    where
        K: core::fmt::Debug,
    {
        let mut req = Self::from_chain_tip(chain_tip);
        for (keychain, spks) in index.all_unbounded_spk_iters() {
            req = req.set_spks_for_keychain(keychain, spks);
        }
        req
    }

    /// Set the [`Script`]s for a given `keychain`.
    ///
    /// This consumes the [`FullScanRequest`] and returns the updated one.
    #[must_use]
    pub fn set_spks_for_keychain(
        mut self,
        keychain: K,
        spks: impl IntoIterator<IntoIter = impl Iterator<Item = Indexed<ScriptBuf>> + Send + 'static>,
    ) -> Self {
        self.spks_by_keychain
            .insert(keychain, Box::new(spks.into_iter()));
        self
    }

    /// Chain on additional [`Script`]s that will be synced against.
    ///
    /// This consumes the [`FullScanRequest`] and returns the updated one.
    #[must_use]
    pub fn chain_spks_for_keychain(
        mut self,
        keychain: K,
        spks: impl IntoIterator<IntoIter = impl Iterator<Item = Indexed<ScriptBuf>> + Send + 'static>,
    ) -> Self {
        match self.spks_by_keychain.remove(&keychain) {
            // clippy here suggests to remove `into_iter` from `spks.into_iter()`, but doing so
            // results in a compilation error
            #[allow(clippy::useless_conversion)]
            Some(keychain_spks) => self
                .spks_by_keychain
                .insert(keychain, Box::new(keychain_spks.chain(spks.into_iter()))),
            None => self
                .spks_by_keychain
                .insert(keychain, Box::new(spks.into_iter())),
        };
        self
    }

    /// Add a closure that will be called for every [`Script`] previously added to any keychain in
    /// this request.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn inspect_spks_for_all_keychains(
        mut self,
        inspect: impl FnMut(K, u32, &Script) + Send + Sync + Clone + 'static,
    ) -> Self
    where
        K: Send + 'static,
    {
        for (keychain, spks) in core::mem::take(&mut self.spks_by_keychain) {
            let mut inspect = inspect.clone();
            self.spks_by_keychain.insert(
                keychain.clone(),
                Box::new(spks.inspect(move |(i, spk)| inspect(keychain.clone(), *i, spk))),
            );
        }
        self
    }

    /// Add a closure that will be called for every [`Script`] previously added to a given
    /// `keychain` in this request.
    ///
    /// This consumes the [`SyncRequest`] and returns the updated one.
    #[must_use]
    pub fn inspect_spks_for_keychain(
        mut self,
        keychain: K,
        mut inspect: impl FnMut(u32, &Script) + Send + Sync + 'static,
    ) -> Self
    where
        K: Send + 'static,
    {
        if let Some(spks) = self.spks_by_keychain.remove(&keychain) {
            self.spks_by_keychain.insert(
                keychain,
                Box::new(spks.inspect(move |(i, spk)| inspect(*i, spk))),
            );
        }
        self
    }
}

/// Data returned from a spk-based blockchain client full scan.
///
/// See also [`FullScanRequest`].
pub struct FullScanResult<K, A = ConfirmationBlockTime> {
    /// The update to apply to the receiving [`LocalChain`](crate::local_chain::LocalChain).
    pub graph_update: TxGraph<A>,
    /// The update to apply to the receiving [`TxGraph`].
    pub chain_update: CheckPoint,
    /// Last active indices for the corresponding keychains (`K`).
    pub last_active_indices: BTreeMap<K, u32>,
}

/// A version of [`core::iter::Chain`] which can combine two [`ExactSizeIterator`]s to form a new
/// [`ExactSizeIterator`].
///
/// The danger of this is explained in [the `ExactSizeIterator` docs]
/// (https://doc.rust-lang.org/core/iter/trait.ExactSizeIterator.html#when-shouldnt-an-adapter-be-exactsizeiterator).
/// This does not apply here since it would be impossible to scan an item count that overflows
/// `usize` anyway.
struct ExactSizeChain<A, B, I> {
    a: Option<A>,
    b: Option<B>,
    i: PhantomData<I>,
}

impl<A, B, I> ExactSizeChain<A, B, I> {
    fn new(a: A, b: B) -> Self {
        ExactSizeChain {
            a: Some(a),
            b: Some(b),
            i: PhantomData,
        }
    }
}

impl<A, B, I> Iterator for ExactSizeChain<A, B, I>
where
    A: Iterator<Item = I>,
    B: Iterator<Item = I>,
{
    type Item = I;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(a) = &mut self.a {
            let item = a.next();
            if item.is_some() {
                return item;
            }
            self.a = None;
        }
        if let Some(b) = &mut self.b {
            let item = b.next();
            if item.is_some() {
                return item;
            }
            self.b = None;
        }
        None
    }
}

impl<A, B, I> ExactSizeIterator for ExactSizeChain<A, B, I>
where
    A: ExactSizeIterator<Item = I>,
    B: ExactSizeIterator<Item = I>,
{
    fn len(&self) -> usize {
        let a_len = self.a.as_ref().map(|a| a.len()).unwrap_or(0);
        let b_len = self.b.as_ref().map(|a| a.len()).unwrap_or(0);
        a_len + b_len
    }
}