bitcoin-heuristics 0.1.0

Pattern detection heuristics for Bitcoin on-chain analytics — consolidations, distributions, CoinJoin, fee spikes, dormant supply reactivation 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
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
pub mod address_reuse;
pub mod coinjoin_detection;
pub mod consolidation;
pub mod distribution;
pub mod hft_consolidation;
pub mod long_term_supply_activation;
pub mod round_value;
pub mod urgent_execution;

use evidence_chain::EvidenceChain;

use crate::match_result::HeuristicMatch;
use crate::models::TxFeatures;

// ─── Heuristic Status ─────────────────────────────────────────────────────────

/// Execution status of a heuristic in the registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeuristicStatus {
    /// Active heuristic: executed and its matches are returned.
    Active,
    /// Experimental heuristic: executed but may have higher false-positive rate.
    Experimental,
    /// Deprecated heuristic: not executed.
    Deprecated,
}

// ─── Heuristic Trait ──────────────────────────────────────────────────────────

/// Common interface for all pattern detection heuristics.
///
/// Implementations must be **pure** (no blocking I/O): they receive [`TxFeatures`] and return
/// `Option<HeuristicMatch>`. RPC operations should be performed by the caller via
/// `tokio::task::spawn_blocking` before populating `TxFeatures::utxo_ages_blocks`.
pub trait Heuristic: Send + Sync {
    /// Unique and immutable identifier (e.g., `"institutional-consolidation-v1"`).
    fn id(&self) -> &'static str;

    /// Semantic version (e.g., `"1.0.0"`).
    fn version(&self) -> &'static str;

    /// Event trigger scope: `"transaction"` or `"block"`.
    fn trigger_scope(&self) -> &'static str {
        "transaction"
    }

    /// Current status of the heuristic.
    fn status(&self) -> HeuristicStatus;

    /// Evaluates transaction features and returns a match if the pattern is detected.
    ///
    /// Returns `None` if the transaction does not match this heuristic's pattern.
    fn evaluate(&self, features: &TxFeatures) -> Option<HeuristicMatch>;

    /// Generates [`EvidenceChain`] for features that triggered this heuristic.
    ///
    /// Default implementation returns `None`.
    /// Should be implemented in heuristics that return `Some` in `evaluate()`.
    fn build_evidence(&self, _features: &TxFeatures) -> Option<EvidenceChain> {
        None
    }
}

// ─── HeuristicRegistry ────────────────────────────────────────────────────────

/// Central registry of all available heuristics.
///
/// Maintains an ordered list of heuristics and executes all Active/Experimental ones
/// on each transaction, collecting the detected pattern matches.
///
/// # Example
///
/// ```
/// use bitcoin_heuristics::{HeuristicRegistry, TxFeatures};
///
/// let registry = HeuristicRegistry::default_registry(0.7);
/// let features = TxFeatures::default();
/// let matches = registry.evaluate_all(&features);
/// println!("Detected {} pattern(s)", matches.len());
/// ```
pub struct HeuristicRegistry {
    heuristics: Vec<(Box<dyn Heuristic>, HeuristicStatus)>,
}

impl HeuristicRegistry {
    /// Creates a new empty registry.
    pub fn new() -> Self {
        Self {
            heuristics: Vec::new(),
        }
    }

    /// Builds the default registry with all bundled heuristics.
    ///
    /// `coinjoin_score_threshold` controls the minimum `coinjoin_score` in
    /// `TxFeatures` required to fire the CoinJoin detection heuristic.
    pub fn default_registry(coinjoin_score_threshold: f64) -> Self {
        let mut registry = Self::new();

        registry.register(
            Box::new(consolidation::UtxoConsolidationHeuristic),
            HeuristicStatus::Active,
        );
        registry.register(
            Box::new(coinjoin_detection::CoinJoinDetectionHeuristic {
                score_threshold: coinjoin_score_threshold,
            }),
            HeuristicStatus::Experimental,
        );
        registry.register(
            Box::new(distribution::DistributionHeuristic),
            HeuristicStatus::Active,
        );
        registry.register(
            Box::new(urgent_execution::UrgentExecutionHeuristic::default()),
            HeuristicStatus::Active,
        );
        registry.register(
            Box::new(round_value::RoundValueHeuristic::default()),
            HeuristicStatus::Experimental,
        );
        registry.register(
            Box::new(address_reuse::AddressReuseDetectionHeuristic::default()),
            HeuristicStatus::Experimental,
        );
        registry.register(
            Box::new(hft_consolidation::HftConsolidationHeuristic),
            HeuristicStatus::Experimental,
        );
        // LongTermSupplyActivationHeuristic requires a BitcoinRpc implementation.
        // Add it manually via register() when RPC is available.

        registry
    }

    /// Registers a heuristic with its status.
    pub fn register(&mut self, heuristic: Box<dyn Heuristic>, status: HeuristicStatus) {
        self.heuristics.push((heuristic, status));
    }

    /// Executes all Active and Experimental heuristics on the given features.
    ///
    /// For each detected match, calls `build_evidence()` and attaches the
    /// `EvidenceChain` to the returned `HeuristicMatch`.
    ///
    /// Deprecated heuristics are silently skipped.
    pub fn evaluate_all(&self, features: &TxFeatures) -> Vec<HeuristicMatch> {
        let mut results = Vec::new();
        for (h, status) in &self.heuristics {
            match status {
                HeuristicStatus::Deprecated => continue,
                HeuristicStatus::Active | HeuristicStatus::Experimental => {
                    if let Some(mut result) = h.evaluate(features) {
                        result.evidence = h.build_evidence(features);
                        results.push(result);
                    }
                }
            }
        }
        results
    }

    /// Calls `build_evidence()` on the heuristic with the given id.
    ///
    /// Returns `None` if the heuristic is not registered or does not implement evidence.
    pub fn build_evidence_for(
        &self,
        heuristic_id: &str,
        features: &TxFeatures,
    ) -> Option<EvidenceChain> {
        self.heuristics
            .iter()
            .find(|(h, _)| h.id() == heuristic_id)
            .and_then(|(h, _)| h.build_evidence(features))
    }

    /// Returns the number of registered heuristics (including Deprecated).
    pub fn len(&self) -> usize {
        self.heuristics.len()
    }

    /// Returns true if there are no registered heuristics.
    pub fn is_empty(&self) -> bool {
        self.heuristics.is_empty()
    }
}

impl Default for HeuristicRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use evidence_chain::EvidenceCategory;

    struct AlwaysFireHeuristic;
    impl Heuristic for AlwaysFireHeuristic {
        fn id(&self) -> &'static str {
            "always-fire"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        fn status(&self) -> HeuristicStatus {
            HeuristicStatus::Active
        }
        fn evaluate(&self, features: &TxFeatures) -> Option<HeuristicMatch> {
            Some(HeuristicMatch::new(
                self.id(),
                self.version(),
                "test_event",
                "test",
                self.trigger_scope(),
                "test".to_string(),
                serde_json::json!({"block_height": features.block_height}),
            ))
        }
    }

    struct NeverFireHeuristic;
    impl Heuristic for NeverFireHeuristic {
        fn id(&self) -> &'static str {
            "never-fire"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        fn status(&self) -> HeuristicStatus {
            HeuristicStatus::Active
        }
        fn evaluate(&self, _features: &TxFeatures) -> Option<HeuristicMatch> {
            None
        }
    }

    struct DeprecatedHeuristic;
    impl Heuristic for DeprecatedHeuristic {
        fn id(&self) -> &'static str {
            "deprecated"
        }
        fn version(&self) -> &'static str {
            "0.1.0"
        }
        fn status(&self) -> HeuristicStatus {
            HeuristicStatus::Deprecated
        }
        fn evaluate(&self, _features: &TxFeatures) -> Option<HeuristicMatch> {
            panic!("deprecated heuristic should never be called")
        }
    }

    fn make_features() -> TxFeatures {
        TxFeatures {
            txid: vec![0xaau8; 32],
            block_height: 840_000,
            block_timestamp: Utc::now(),
            input_count: 1,
            output_count: 2,
            is_coinbase: false,
            total_input_value: 100_000,
            total_output_value: 99_000,
            fee: 1_000,
            output_value_min: 40_000,
            output_value_max: 59_000,
            output_value_median: 49_500.0,
            fee_rate_sat_vb: Some(5.0),
            input_p2pkh_count: 1,
            output_p2pkh_count: 2,
            is_simple_send: true,
            tx_vsize_vbytes: 200,
            tx_version: 1,
            input_utxo_refs: vec![(vec![0xffu8; 32], 0)],
            output_values: vec![40_000, 59_000],
            block_price_usd: Some(50_000.0),
            ..Default::default()
        }
    }

    fn make_consolidation_features() -> TxFeatures {
        let mut f = make_features();
        f.input_count = 15;
        f.output_count = 2;
        f.is_consolidation = true;
        f.total_input_value = 2_000_000_000;
        f.total_output_value = 1_990_000_000;
        f.output_value_max = 1_900_000_000;
        f.block_price_usd = Some(60_000.0);
        f.is_input_script_homogeneous = true;
        f
    }

    #[test]
    fn test_registry_empty() {
        let registry = HeuristicRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_registry_always_fire() {
        let mut registry = HeuristicRegistry::new();
        registry.register(Box::new(AlwaysFireHeuristic), HeuristicStatus::Active);
        let results = registry.evaluate_all(&make_features());
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].event_type, "test_event");
    }

    #[test]
    fn test_registry_never_fire() {
        let mut registry = HeuristicRegistry::new();
        registry.register(Box::new(NeverFireHeuristic), HeuristicStatus::Active);
        let results = registry.evaluate_all(&make_features());
        assert!(results.is_empty());
    }

    #[test]
    fn test_registry_deprecated_skipped() {
        let mut registry = HeuristicRegistry::new();
        registry.register(Box::new(DeprecatedHeuristic), HeuristicStatus::Deprecated);
        let results = registry.evaluate_all(&make_features());
        assert!(results.is_empty());
    }

    #[test]
    fn test_registry_multiple_heuristics() {
        let mut registry = HeuristicRegistry::new();
        registry.register(Box::new(AlwaysFireHeuristic), HeuristicStatus::Active);
        registry.register(Box::new(NeverFireHeuristic), HeuristicStatus::Active);
        registry.register(Box::new(DeprecatedHeuristic), HeuristicStatus::Deprecated);
        assert_eq!(registry.len(), 3);
        let results = registry.evaluate_all(&make_features());
        assert_eq!(results.len(), 1, "only AlwaysFireHeuristic should fire");
    }

    #[test]
    fn test_default_registry_not_empty() {
        let registry = HeuristicRegistry::default_registry(0.7);
        assert!(
            !registry.is_empty(),
            "default registry should have heuristics"
        );
    }

    #[test]
    fn test_registry_coinjoin_threshold_no_event() {
        let registry = HeuristicRegistry::default_registry(0.9);
        let mut f = make_features();
        f.coinjoin_score = 0.85;
        let results = registry.evaluate_all(&f);
        assert!(
            !results.iter().any(|r| r.event_type == "coinjoin_detected"),
            "score 0.85 with threshold 0.9 should not fire coinjoin"
        );
    }

    #[test]
    fn test_registry_coinjoin_threshold_fires() {
        let registry = HeuristicRegistry::default_registry(0.7);
        let mut f = make_features();
        f.coinjoin_score = 0.85;
        f.input_count = 5;
        f.output_count = 5;
        f.has_equal_outputs = true;
        let results = registry.evaluate_all(&f);
        assert!(
            results.iter().any(|r| r.event_type == "coinjoin_detected"),
            "score 0.85 with threshold 0.7 should fire coinjoin"
        );
    }

    #[test]
    fn test_consolidation_build_evidence() {
        let h = consolidation::UtxoConsolidationHeuristic;
        let f = make_consolidation_features();
        let chain = h.build_evidence(&f);
        assert!(
            chain.is_some(),
            "build_evidence should return Some for consolidation"
        );
        let chain = chain.unwrap();
        assert!(
            chain.links.len() >= 2,
            "should have ≥2 links, has {}",
            chain.links.len()
        );
        assert!(
            chain.strength.passed_checks >= 1,
            "at least 1 check should pass"
        );
    }

    #[test]
    fn test_distribution_build_evidence() {
        let h = distribution::DistributionHeuristic;
        let mut f = make_features();
        f.input_count = 2;
        f.output_count = 50;
        f.is_distribution = true;
        f.total_output_value = 199_990_000;
        f.output_p2wpkh_count = 50;
        let chain = h.build_evidence(&f);
        assert!(
            chain.is_some(),
            "build_evidence should return Some for distribution"
        );
        let chain = chain.unwrap();
        assert!(
            chain.links.len() >= 2,
            "should have ≥2 links, has {}",
            chain.links.len()
        );
    }

    #[test]
    fn test_coinjoin_build_evidence() {
        let h = coinjoin_detection::CoinJoinDetectionHeuristic::default();
        let mut f = make_features();
        f.coinjoin_score = 0.9;
        f.input_count = 5;
        f.output_count = 5;
        f.has_equal_outputs = true;
        let chain = h.build_evidence(&f);
        assert!(
            chain.is_some(),
            "build_evidence should return Some for coinjoin"
        );
        let chain = chain.unwrap();
        let has_behavioral = chain
            .links
            .iter()
            .any(|l| l.category == EvidenceCategory::Behavioral);
        assert!(
            has_behavioral,
            "should have Behavioral link with coinjoin_score"
        );
    }

    #[test]
    fn test_registry_build_evidence_for() {
        let mut registry = HeuristicRegistry::new();
        registry.register(
            Box::new(consolidation::UtxoConsolidationHeuristic),
            HeuristicStatus::Active,
        );
        let f = make_consolidation_features();
        let chain = registry.build_evidence_for("institutional-consolidation-v1", &f);
        assert!(
            chain.is_some(),
            "build_evidence_for should find heuristic by id"
        );
    }

    #[test]
    fn test_consolidation_summary_format() {
        let h = consolidation::UtxoConsolidationHeuristic;
        let f = make_consolidation_features();
        let result = h.evaluate(&f).unwrap();
        assert!(
            result.summary.contains("inputs"),
            "summary should mention 'inputs'"
        );
        assert!(
            result.summary.contains("outputs"),
            "summary should mention 'outputs'"
        );
        assert!(
            result.summary.contains(&f.block_height.to_string()),
            "summary should mention block_height"
        );
    }

    #[test]
    fn test_summary_no_forbidden_language() {
        let registry = HeuristicRegistry::default_registry(0.7);
        let forbidden = [
            "suspicious",
            "malicious",
            "laundering",
            "illegal",
            "criminal",
            "fraud",
            "scam",
        ];

        let results = registry.evaluate_all(&make_consolidation_features());
        for result in &results {
            for word in &forbidden {
                assert!(
                    !result.summary.to_lowercase().contains(word),
                    "heuristic '{}' summary contains forbidden language '{}'",
                    result.id,
                    word
                );
            }
        }
    }

    #[test]
    fn test_evidence_populated_by_registry() {
        let registry = HeuristicRegistry::default_registry(0.7);
        let f = make_consolidation_features();
        let results = registry.evaluate_all(&f);
        let consolidation_result = results
            .iter()
            .find(|r| r.event_type == "institutional_consolidation");
        assert!(consolidation_result.is_some(), "consolidation should fire");
        assert!(
            consolidation_result.unwrap().evidence.is_some(),
            "registry should populate evidence field"
        );
    }
}