bsv-rs 0.3.5

BSV blockchain SDK for Rust - primitives, script, transactions, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Transaction history traversal.
//!
//! The Historian builds a chronological history of values by traversing
//! a transaction's input ancestry and interpreting each output with a
//! provided interpreter function.
//!
//! This is useful for protocols that track state changes over time, such as
//! token transfers or key-value stores.

use crate::transaction::Transaction;
use crate::Result;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;

/// Interpreter function type.
///
/// Given a transaction, output index, and optional context, returns an optional
/// value of type T. Returning `None` means the output does not contribute to
/// history.
///
/// # Type Parameters
///
/// * `T` - The decoded/typed value produced for a matching output
/// * `C` - The per-call context passed through Historian to the interpreter
pub type InterpreterFn<T, C> = Box<
    dyn Fn(&Transaction, u32, Option<&C>) -> Pin<Box<dyn Future<Output = Option<T>>>> + Send + Sync,
>;

/// Configuration for the Historian.
#[derive(Default)]
#[allow(clippy::type_complexity)]
pub struct HistorianConfig<T, C> {
    /// Enable debug logging.
    pub debug: bool,
    /// Cache for history results.
    pub history_cache: Option<HashMap<String, Vec<T>>>,
    /// Version string for cache key (bump when interpreter semantics change).
    pub interpreter_version: Option<String>,
    /// Function to generate cache key from context.
    pub ctx_key_fn: Option<Box<dyn Fn(Option<&C>) -> String + Send + Sync>>,
}

/// Traverses transaction ancestry to build history.
///
/// Uses an interpreter function to extract values from transaction outputs,
/// then follows input sources recursively to build a chronological history.
///
/// # Type Parameters
///
/// * `T` - The value type produced by the interpreter
/// * `C` - The context type passed to the interpreter
///
/// # Example
///
/// ```rust,ignore
/// use bsv_rs::overlay::Historian;
///
/// // Define an interpreter that extracts token amounts
/// let interpreter = Box::new(|tx, output_idx, ctx| {
///     Box::pin(async move {
///         // Parse token data from output
///         // Return Some(amount) if valid, None otherwise
///         Some(100u64)
///     })
/// });
///
/// let historian = Historian::new(interpreter, Default::default());
/// let history = historian.build_history(&tip_tx, None).await?;
/// ```
#[allow(clippy::type_complexity)]
pub struct Historian<T, C> {
    interpreter: InterpreterFn<T, C>,
    debug: bool,
    history_cache: Option<tokio::sync::RwLock<HashMap<String, Vec<T>>>>,
    interpreter_version: String,
    ctx_key_fn: Option<Box<dyn Fn(Option<&C>) -> String + Send + Sync>>,
}

impl<T: Clone + Send + Sync + 'static, C: Send + Sync + 'static> Historian<T, C> {
    /// Create a new Historian with the given interpreter.
    ///
    /// # Arguments
    ///
    /// * `interpreter` - Function to interpret transaction outputs
    /// * `config` - Configuration options
    pub fn new(interpreter: InterpreterFn<T, C>, config: HistorianConfig<T, C>) -> Self {
        Self {
            interpreter,
            debug: config.debug,
            history_cache: config.history_cache.map(tokio::sync::RwLock::new),
            interpreter_version: config
                .interpreter_version
                .unwrap_or_else(|| "v1".to_string()),
            ctx_key_fn: config.ctx_key_fn,
        }
    }

    /// Build history starting from a transaction.
    ///
    /// Recursively traverses input sources, collecting interpreter results.
    /// Returns values in chronological order (oldest first).
    ///
    /// # Arguments
    ///
    /// * `start_transaction` - The transaction to start traversal from
    /// * `context` - Optional context to pass to the interpreter
    ///
    /// # Returns
    ///
    /// A vector of values in chronological order (oldest first).
    pub async fn build_history(
        &self,
        start_transaction: &Transaction,
        context: Option<&C>,
    ) -> Result<Vec<T>> {
        // Check cache first
        let cache_key = self.cache_key(start_transaction, context);
        if let Some(ref cache) = self.history_cache {
            let cache_read = cache.read().await;
            if let Some(cached) = cache_read.get(&cache_key) {
                if self.debug {
                    eprintln!("[Historian] Cache hit: {}", cache_key);
                }
                return Ok(cached.clone());
            }
        }

        let mut visited: HashSet<String> = HashSet::new();
        let mut results: Vec<T> = Vec::new();

        self.traverse(start_transaction, context, &mut visited, &mut results)
            .await?;

        // Reverse for chronological order (oldest first)
        results.reverse();

        // Cache result
        if let Some(ref cache) = self.history_cache {
            let mut cache_write = cache.write().await;
            cache_write.insert(cache_key.clone(), results.clone());
            if self.debug {
                eprintln!("[Historian] Cached: {}", cache_key);
            }
        }

        Ok(results)
    }

    /// Recursive traversal helper.
    fn traverse<'a>(
        &'a self,
        tx: &'a Transaction,
        context: Option<&'a C>,
        visited: &'a mut HashSet<String>,
        results: &'a mut Vec<T>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>>
    where
        T: 'a,
        C: 'a,
    {
        Box::pin(async move {
            let txid = tx.id();

            // Prevent cycles
            if visited.contains(&txid) {
                if self.debug {
                    eprintln!("[Historian] Skipping visited: {}", txid);
                }
                return Ok(());
            }
            visited.insert(txid.clone());

            if self.debug {
                eprintln!("[Historian] Processing: {}", txid);
            }

            // Interpret each output
            for (idx, _output) in tx.outputs.iter().enumerate() {
                if let Some(value) = (self.interpreter)(tx, idx as u32, context).await {
                    results.push(value);
                    if self.debug {
                        eprintln!("[Historian] Found value at output {}", idx);
                    }
                }
            }

            // Traverse input sources
            for input in &tx.inputs {
                if let Some(ref source_tx) = input.source_transaction {
                    self.traverse(source_tx, context, visited, results).await?;
                } else if self.debug {
                    eprintln!("[Historian] Input missing source transaction");
                }
            }

            Ok(())
        })
    }

    /// Generate cache key for a transaction and context.
    fn cache_key(&self, tx: &Transaction, context: Option<&C>) -> String {
        let txid = tx.id();
        let ctx_key = self
            .ctx_key_fn
            .as_ref()
            .map(|f| f(context))
            .unwrap_or_default();

        format!("{}|{}|{}", self.interpreter_version, txid, ctx_key)
    }
}

/// Synchronous version of Historian for simpler use cases.
///
/// This version uses a synchronous interpreter function and does not
/// require async/await.
#[allow(clippy::type_complexity)]
pub struct SyncHistorian<T, C> {
    interpreter: Box<dyn Fn(&Transaction, u32, Option<&C>) -> Option<T> + Send + Sync>,
    debug: bool,
    #[allow(dead_code)]
    interpreter_version: String,
}

impl<T: Clone + Send + Sync, C: Send + Sync> SyncHistorian<T, C> {
    /// Create a new synchronous Historian.
    pub fn new<F>(interpreter: F) -> Self
    where
        F: Fn(&Transaction, u32, Option<&C>) -> Option<T> + Send + Sync + 'static,
    {
        Self {
            interpreter: Box::new(interpreter),
            debug: false,
            interpreter_version: "v1".to_string(),
        }
    }

    /// Enable debug logging.
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Set interpreter version for cache invalidation.
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.interpreter_version = version.into();
        self
    }

    /// Build history starting from a transaction.
    ///
    /// Returns values in chronological order (oldest first).
    pub fn build_history(&self, start_transaction: &Transaction, context: Option<&C>) -> Vec<T> {
        let mut visited: HashSet<String> = HashSet::new();
        let mut results: Vec<T> = Vec::new();

        self.traverse(start_transaction, context, &mut visited, &mut results);

        // Reverse for chronological order (oldest first)
        results.reverse();
        results
    }

    /// Recursive traversal helper.
    fn traverse(
        &self,
        tx: &Transaction,
        context: Option<&C>,
        visited: &mut HashSet<String>,
        results: &mut Vec<T>,
    ) {
        let txid = tx.id();

        // Prevent cycles
        if visited.contains(&txid) {
            return;
        }
        visited.insert(txid.clone());

        if self.debug {
            eprintln!("[SyncHistorian] Processing: {}", txid);
        }

        // Interpret each output
        for (idx, _output) in tx.outputs.iter().enumerate() {
            if let Some(value) = (self.interpreter)(tx, idx as u32, context) {
                results.push(value);
            }
        }

        // Traverse input sources
        for input in &tx.inputs {
            if let Some(ref source_tx) = input.source_transaction {
                self.traverse(source_tx, context, visited, results);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::script::LockingScript;
    use crate::transaction::{TransactionInput, TransactionOutput};

    fn create_test_tx(_id_suffix: u8, source: Option<Transaction>) -> Transaction {
        let mut tx = Transaction::new();
        tx.outputs.push(TransactionOutput::new(
            1000,
            LockingScript::from_asm("OP_TRUE").unwrap(),
        ));

        if let Some(source_tx) = source {
            let mut input = TransactionInput::new(source_tx.id(), 0);
            input.source_transaction = Some(Box::new(source_tx));
            tx.inputs.push(input);
        }

        tx
    }

    #[test]
    fn test_sync_historian_single_tx() {
        let tx = create_test_tx(1, None);

        let historian = SyncHistorian::<u32, ()>::new(|_tx, output_idx, _ctx| Some(output_idx));

        let history = historian.build_history(&tx, None);
        assert_eq!(history, vec![0]);
    }

    #[test]
    fn test_sync_historian_chain() {
        // Create a chain: tx1 <- tx2 <- tx3
        let tx1 = create_test_tx(1, None);
        let tx2 = create_test_tx(2, Some(tx1));
        let tx3 = create_test_tx(3, Some(tx2));

        let historian = SyncHistorian::<String, ()>::new(|tx, _output_idx, _ctx| Some(tx.id()));

        let history = historian.build_history(&tx3, None);

        // Should be in chronological order (oldest first)
        assert_eq!(history.len(), 3);
    }

    #[test]
    fn test_sync_historian_filters() {
        let tx = create_test_tx(1, None);

        // Interpreter that filters some outputs
        let historian = SyncHistorian::<u32, ()>::new(|_tx, output_idx, _ctx| {
            if output_idx % 2 == 0 {
                Some(output_idx)
            } else {
                None
            }
        });

        let history = historian.build_history(&tx, None);
        // Single output at index 0 (even)
        assert_eq!(history, vec![0]);
    }

    #[test]
    fn test_sync_historian_with_context() {
        let tx = create_test_tx(1, None);

        let historian =
            SyncHistorian::<u32, u32>::new(|_tx, output_idx, ctx| ctx.map(|c| output_idx + c));

        let history_with_ctx = historian.build_history(&tx, Some(&10));
        assert_eq!(history_with_ctx, vec![10]);

        let history_without_ctx = historian.build_history(&tx, None);
        assert!(history_without_ctx.is_empty());
    }

    #[test]
    fn test_sync_historian_prevents_cycles() {
        // Create a tx that references itself (shouldn't happen in practice)
        let tx = create_test_tx(1, None);

        let historian = SyncHistorian::<u32, ()>::new(|_tx, output_idx, _ctx| Some(output_idx));

        // Should not infinite loop
        let history = historian.build_history(&tx, None);
        assert_eq!(history.len(), 1);
    }

    #[tokio::test]
    async fn test_async_historian_basic() {
        let tx = create_test_tx(1, None);

        let interpreter: InterpreterFn<u32, ()> =
            Box::new(|_tx, output_idx, _ctx| Box::pin(async move { Some(output_idx) }));

        let historian = Historian::new(interpreter, HistorianConfig::default());
        let history = historian.build_history(&tx, None).await.unwrap();

        assert_eq!(history, vec![0]);
    }

    #[tokio::test]
    async fn test_async_historian_with_cache() {
        let tx = create_test_tx(1, None);

        let interpreter: InterpreterFn<u32, ()> =
            Box::new(|_tx, output_idx, _ctx| Box::pin(async move { Some(output_idx) }));

        let config = HistorianConfig {
            debug: false,
            history_cache: Some(HashMap::new()),
            interpreter_version: Some("v1".to_string()),
            ctx_key_fn: None,
        };

        let historian = Historian::new(interpreter, config);

        // First call populates cache
        let history1 = historian.build_history(&tx, None).await.unwrap();
        // Second call should use cache
        let history2 = historian.build_history(&tx, None).await.unwrap();

        assert_eq!(history1, history2);
    }
}