kaccy-bitcoin 0.2.0

Bitcoin integration for Kaccy Protocol - HD wallets, UTXO management, and transaction building
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Transaction history with pagination, filtering, and export

use bitcoin::Txid;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::debug;

use crate::error::Result;

/// Transaction type for categorization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionType {
    /// Bitcoin received from an external address.
    Received,
    /// Bitcoin sent to an external address.
    Sent,
    /// Transfer between addresses owned by the same wallet.
    SelfTransfer,
    /// Transaction type could not be determined.
    Unknown,
}

/// Transaction record for history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoricalTransaction {
    /// Transaction identifier on the Bitcoin network.
    pub txid: Txid,
    /// Categorization of the transaction direction.
    pub tx_type: TransactionType,
    /// Net amount in satoshis (positive = received, negative = sent).
    pub amount_sats: i64,
    /// Miner fee paid in satoshis, if known.
    pub fee_sats: Option<u64>,
    /// Number of block confirmations; `0` means still in mempool.
    pub confirmations: u32,
    /// Block height at which the transaction was confirmed.
    pub block_height: Option<u64>,
    /// Timestamp from the block header when confirmed.
    pub block_time: Option<DateTime<Utc>>,
    /// Local timestamp when the transaction was first seen.
    pub timestamp: DateTime<Utc>,
    /// Bitcoin addresses involved in this transaction.
    pub addresses: Vec<String>,
    /// User-assigned label for this transaction.
    pub label: Option<String>,
    /// User-written notes attached to this transaction.
    pub notes: Option<String>,
}

/// Filter for querying transaction history
#[derive(Debug, Clone, Default)]
pub struct TransactionFilter {
    /// Filter by transaction type
    pub tx_type: Option<TransactionType>,
    /// Filter by minimum amount (in satoshis)
    pub min_amount: Option<i64>,
    /// Filter by maximum amount (in satoshis)
    pub max_amount: Option<i64>,
    /// Filter by start date
    pub start_date: Option<DateTime<Utc>>,
    /// Filter by end date
    pub end_date: Option<DateTime<Utc>>,
    /// Filter by minimum confirmations
    pub min_confirmations: Option<u32>,
    /// Filter by address
    pub address: Option<String>,
    /// Filter by label
    pub label: Option<String>,
    /// Search query (searches in labels, notes, addresses)
    pub search_query: Option<String>,
}

impl TransactionFilter {
    /// Create a new empty filter
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by transaction type
    pub fn with_type(mut self, tx_type: TransactionType) -> Self {
        self.tx_type = Some(tx_type);
        self
    }

    /// Filter by amount range
    pub fn with_amount_range(mut self, min: Option<i64>, max: Option<i64>) -> Self {
        self.min_amount = min;
        self.max_amount = max;
        self
    }

    /// Filter by date range
    pub fn with_date_range(
        mut self,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
    ) -> Self {
        self.start_date = start;
        self.end_date = end;
        self
    }

    /// Filter by minimum confirmations
    pub fn with_min_confirmations(mut self, min_conf: u32) -> Self {
        self.min_confirmations = Some(min_conf);
        self
    }

    /// Filter by address
    pub fn with_address(mut self, address: String) -> Self {
        self.address = Some(address);
        self
    }

    /// Filter by search query
    pub fn with_search(mut self, query: String) -> Self {
        self.search_query = Some(query);
        self
    }

    /// Check if a transaction matches this filter
    pub fn matches(&self, tx: &HistoricalTransaction) -> bool {
        // Type filter
        if let Some(tx_type) = self.tx_type {
            if tx.tx_type != tx_type {
                return false;
            }
        }

        // Amount filters
        if let Some(min) = self.min_amount {
            if tx.amount_sats.abs() < min.abs() {
                return false;
            }
        }

        if let Some(max) = self.max_amount {
            if tx.amount_sats.abs() > max.abs() {
                return false;
            }
        }

        // Date filters
        if let Some(start) = self.start_date {
            if tx.timestamp < start {
                return false;
            }
        }

        if let Some(end) = self.end_date {
            if tx.timestamp > end {
                return false;
            }
        }

        // Confirmations filter
        if let Some(min_conf) = self.min_confirmations {
            if tx.confirmations < min_conf {
                return false;
            }
        }

        // Address filter
        if let Some(ref addr) = self.address {
            if !tx.addresses.contains(addr) {
                return false;
            }
        }

        // Label filter
        if let Some(ref label) = self.label {
            if tx.label.as_ref() != Some(label) {
                return false;
            }
        }

        // Search query (searches in labels, notes, addresses, txid)
        if let Some(ref query) = self.search_query {
            let query_lower = query.to_lowercase();
            let matches = tx
                .label
                .as_ref()
                .is_some_and(|l| l.to_lowercase().contains(&query_lower))
                || tx
                    .notes
                    .as_ref()
                    .is_some_and(|n| n.to_lowercase().contains(&query_lower))
                || tx
                    .addresses
                    .iter()
                    .any(|a| a.to_lowercase().contains(&query_lower))
                || tx.txid.to_string().contains(&query_lower);

            if !matches {
                return false;
            }
        }

        true
    }
}

/// Pagination options
#[derive(Debug, Clone)]
pub struct PaginationOptions {
    /// Page number (0-indexed)
    pub page: usize,
    /// Items per page
    pub page_size: usize,
    /// Sort by field
    pub sort_by: SortField,
    /// Sort order
    pub sort_order: SortOrder,
}

impl Default for PaginationOptions {
    fn default() -> Self {
        Self {
            page: 0,
            page_size: 50,
            sort_by: SortField::Timestamp,
            sort_order: SortOrder::Descending,
        }
    }
}

/// Fields to sort by
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortField {
    /// Sort by the time the transaction was first seen.
    Timestamp,
    /// Sort by net amount (satoshis).
    Amount,
    /// Sort by number of block confirmations.
    Confirmations,
    /// Sort by the block height at which the transaction was confirmed.
    BlockHeight,
}

/// Sort order
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
    /// Smallest / oldest value first.
    Ascending,
    /// Largest / newest value first.
    Descending,
}

/// Paginated result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedResult {
    /// The transactions on the current page.
    pub transactions: Vec<HistoricalTransaction>,
    /// Total number of transactions matching the filter (across all pages).
    pub total_count: usize,
    /// Current page index (0-based).
    pub page: usize,
    /// Maximum number of transactions per page.
    pub page_size: usize,
    /// Total number of pages given `total_count` and `page_size`.
    pub total_pages: usize,
}

/// Transaction history manager
pub struct TransactionHistory {
    transactions: Vec<HistoricalTransaction>,
    labels: HashMap<Txid, String>,
    notes: HashMap<Txid, String>,
}

impl TransactionHistory {
    /// Create a new transaction history manager
    pub fn new() -> Self {
        Self {
            transactions: Vec::new(),
            labels: HashMap::new(),
            notes: HashMap::new(),
        }
    }

    /// Add a transaction to history
    pub fn add_transaction(&mut self, mut tx: HistoricalTransaction) {
        // Apply labels and notes if available
        if let Some(label) = self.labels.get(&tx.txid) {
            tx.label = Some(label.clone());
        }
        if let Some(notes) = self.notes.get(&tx.txid) {
            tx.notes = Some(notes.clone());
        }

        self.transactions.push(tx);
        debug!(
            count = self.transactions.len(),
            "Transaction added to history"
        );
    }

    /// Set label for a transaction
    pub fn set_label(&mut self, txid: Txid, label: String) {
        self.labels.insert(txid, label.clone());

        // Update existing transaction if present
        if let Some(tx) = self.transactions.iter_mut().find(|t| t.txid == txid) {
            tx.label = Some(label);
        }
    }

    /// Set notes for a transaction
    pub fn set_notes(&mut self, txid: Txid, notes: String) {
        self.notes.insert(txid, notes.clone());

        // Update existing transaction if present
        if let Some(tx) = self.transactions.iter_mut().find(|t| t.txid == txid) {
            tx.notes = Some(notes);
        }
    }

    /// Get transaction by txid
    pub fn get_transaction(&self, txid: &Txid) -> Option<&HistoricalTransaction> {
        self.transactions.iter().find(|t| &t.txid == txid)
    }

    /// Query transactions with filter and pagination
    pub fn query(
        &self,
        filter: Option<&TransactionFilter>,
        pagination: Option<&PaginationOptions>,
    ) -> PaginatedResult {
        // Apply filter
        let mut filtered: Vec<HistoricalTransaction> = if let Some(f) = filter {
            self.transactions
                .iter()
                .filter(|tx| f.matches(tx))
                .cloned()
                .collect()
        } else {
            self.transactions.clone()
        };

        // Sort
        let pagination = pagination.cloned().unwrap_or_default();
        match (pagination.sort_by, pagination.sort_order) {
            (SortField::Timestamp, SortOrder::Ascending) => filtered.sort_by_key(|tx| tx.timestamp),
            (SortField::Timestamp, SortOrder::Descending) => {
                filtered.sort_by_key(|tx| std::cmp::Reverse(tx.timestamp))
            }
            (SortField::Amount, SortOrder::Ascending) => filtered.sort_by_key(|tx| tx.amount_sats),
            (SortField::Amount, SortOrder::Descending) => {
                filtered.sort_by_key(|tx| std::cmp::Reverse(tx.amount_sats))
            }
            (SortField::Confirmations, SortOrder::Ascending) => {
                filtered.sort_by_key(|tx| tx.confirmations)
            }
            (SortField::Confirmations, SortOrder::Descending) => {
                filtered.sort_by_key(|tx| std::cmp::Reverse(tx.confirmations))
            }
            (SortField::BlockHeight, SortOrder::Ascending) => {
                filtered.sort_by_key(|tx| tx.block_height)
            }
            (SortField::BlockHeight, SortOrder::Descending) => {
                filtered.sort_by_key(|tx| std::cmp::Reverse(tx.block_height))
            }
        }

        // Paginate
        let total_count = filtered.len();
        let total_pages = total_count.div_ceil(pagination.page_size);

        let start = pagination.page * pagination.page_size;
        let end = (start + pagination.page_size).min(total_count);

        let transactions = if start < total_count {
            filtered[start..end].to_vec()
        } else {
            Vec::new()
        };

        PaginatedResult {
            transactions,
            total_count,
            page: pagination.page,
            page_size: pagination.page_size,
            total_pages,
        }
    }

    /// Get summary statistics
    pub fn get_summary(&self) -> TransactionSummary {
        let total_received = self
            .transactions
            .iter()
            .filter(|t| t.tx_type == TransactionType::Received)
            .map(|t| t.amount_sats.unsigned_abs())
            .sum();

        let total_sent = self
            .transactions
            .iter()
            .filter(|t| t.tx_type == TransactionType::Sent)
            .map(|t| t.amount_sats.unsigned_abs())
            .sum();

        let total_fees = self.transactions.iter().filter_map(|t| t.fee_sats).sum();

        TransactionSummary {
            total_transactions: self.transactions.len(),
            total_received_sats: total_received,
            total_sent_sats: total_sent,
            total_fees_sats: total_fees,
            confirmed_transactions: self
                .transactions
                .iter()
                .filter(|t| t.confirmations > 0)
                .count(),
            pending_transactions: self
                .transactions
                .iter()
                .filter(|t| t.confirmations == 0)
                .count(),
        }
    }

    /// Export to CSV format
    pub fn export_csv(&self, filter: Option<&TransactionFilter>) -> String {
        let mut csv = String::from(
            "Txid,Type,Amount (sats),Fee (sats),Confirmations,Block Height,Timestamp,Label,Notes\n",
        );

        let transactions = if let Some(f) = filter {
            self.transactions
                .iter()
                .filter(|tx| f.matches(tx))
                .collect::<Vec<_>>()
        } else {
            self.transactions.iter().collect::<Vec<_>>()
        };

        for tx in transactions {
            csv.push_str(&format!(
                "{},{:?},{},{},{},{},{},{},{}\n",
                tx.txid,
                tx.tx_type,
                tx.amount_sats,
                tx.fee_sats.map_or("".to_string(), |f| f.to_string()),
                tx.confirmations,
                tx.block_height.map_or("".to_string(), |h| h.to_string()),
                tx.timestamp.to_rfc3339(),
                tx.label.as_deref().unwrap_or(""),
                tx.notes.as_deref().unwrap_or("")
            ));
        }

        csv
    }

    /// Export to JSON format
    pub fn export_json(&self, filter: Option<&TransactionFilter>) -> Result<String> {
        let transactions = if let Some(f) = filter {
            self.transactions
                .iter()
                .filter(|tx| f.matches(tx))
                .cloned()
                .collect::<Vec<_>>()
        } else {
            self.transactions.clone()
        };

        serde_json::to_string_pretty(&transactions).map_err(|e| {
            crate::error::BitcoinError::Validation(format!("JSON serialization failed: {}", e))
        })
    }

    /// Clear all history
    pub fn clear(&mut self) {
        self.transactions.clear();
        debug!("Transaction history cleared");
    }

    /// Detect address reuse
    pub fn detect_address_reuse(&self) -> Vec<AddressReuseReport> {
        let mut address_usage: HashMap<String, Vec<Txid>> = HashMap::new();

        for tx in &self.transactions {
            for addr in &tx.addresses {
                address_usage.entry(addr.clone()).or_default().push(tx.txid);
            }
        }

        address_usage
            .into_iter()
            .filter(|(_, txids)| txids.len() > 1)
            .map(|(address, txids)| AddressReuseReport {
                address,
                usage_count: txids.len(),
                transactions: txids,
            })
            .collect()
    }
}

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

/// Transaction summary statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionSummary {
    /// Total number of transactions in the history.
    pub total_transactions: usize,
    /// Total amount received across all `Received` transactions (satoshis).
    pub total_received_sats: u64,
    /// Total amount sent across all `Sent` transactions (satoshis).
    pub total_sent_sats: u64,
    /// Total miner fees paid across all transactions (satoshis).
    pub total_fees_sats: u64,
    /// Number of transactions with at least one confirmation.
    pub confirmed_transactions: usize,
    /// Number of transactions still waiting for confirmations.
    pub pending_transactions: usize,
}

impl TransactionSummary {
    /// Get net balance change
    pub fn net_balance_sats(&self) -> i64 {
        self.total_received_sats as i64 - self.total_sent_sats as i64 - self.total_fees_sats as i64
    }

    /// Get balance in BTC
    pub fn net_balance_btc(&self) -> f64 {
        self.net_balance_sats() as f64 / 100_000_000.0
    }
}

/// Address reuse detection report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddressReuseReport {
    /// The Bitcoin address that was reused.
    pub address: String,
    /// Number of transactions that involved this address.
    pub usage_count: usize,
    /// Transaction IDs of all transactions that used this address.
    pub transactions: Vec<Txid>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::hashes::Hash;

    fn create_test_tx(amount: i64, tx_type: TransactionType) -> HistoricalTransaction {
        HistoricalTransaction {
            txid: Txid::all_zeros(),
            tx_type,
            amount_sats: amount,
            fee_sats: Some(1000),
            confirmations: 6,
            block_height: Some(700000),
            block_time: Some(Utc::now()),
            timestamp: Utc::now(),
            addresses: vec!["bc1q...".to_string()],
            label: None,
            notes: None,
        }
    }

    #[test]
    fn test_transaction_filter_new() {
        let filter = TransactionFilter::new();
        assert!(filter.tx_type.is_none());
        assert!(filter.min_amount.is_none());
    }

    #[test]
    fn test_transaction_filter_builder() {
        let filter = TransactionFilter::new()
            .with_type(TransactionType::Received)
            .with_min_confirmations(6);

        assert_eq!(filter.tx_type, Some(TransactionType::Received));
        assert_eq!(filter.min_confirmations, Some(6));
    }

    #[test]
    fn test_transaction_history_add() {
        let mut history = TransactionHistory::new();
        let tx = create_test_tx(100000, TransactionType::Received);

        history.add_transaction(tx);
        assert_eq!(history.transactions.len(), 1);
    }

    #[test]
    fn test_transaction_history_labels() {
        let mut history = TransactionHistory::new();
        let txid = Txid::all_zeros();

        history.set_label(txid, "Test Payment".to_string());
        assert_eq!(history.labels.get(&txid).unwrap(), "Test Payment");

        let tx = create_test_tx(100000, TransactionType::Received);
        history.add_transaction(tx);

        let stored = history.get_transaction(&txid).unwrap();
        assert_eq!(stored.label, Some("Test Payment".to_string()));
    }

    #[test]
    fn test_pagination_defaults() {
        let opts = PaginationOptions::default();
        assert_eq!(opts.page, 0);
        assert_eq!(opts.page_size, 50);
    }

    #[test]
    fn test_transaction_query() {
        let mut history = TransactionHistory::new();

        for i in 0..100 {
            let mut tx = create_test_tx(100000 * i, TransactionType::Received);
            tx.txid = Txid::from_byte_array([i as u8; 32]);
            history.add_transaction(tx);
        }

        let pagination = PaginationOptions {
            page: 0,
            page_size: 10,
            ..Default::default()
        };

        let result = history.query(None, Some(&pagination));
        assert_eq!(result.transactions.len(), 10);
        assert_eq!(result.total_count, 100);
        assert_eq!(result.total_pages, 10);
    }

    #[test]
    fn test_transaction_filter_matches() {
        let filter = TransactionFilter::new().with_type(TransactionType::Received);

        let tx1 = create_test_tx(100000, TransactionType::Received);
        let tx2 = create_test_tx(-100000, TransactionType::Sent);

        assert!(filter.matches(&tx1));
        assert!(!filter.matches(&tx2));
    }

    #[test]
    fn test_transaction_summary() {
        let mut history = TransactionHistory::new();

        history.add_transaction(create_test_tx(100000, TransactionType::Received));
        history.add_transaction(create_test_tx(-50000, TransactionType::Sent));

        let summary = history.get_summary();
        assert_eq!(summary.total_transactions, 2);
        assert_eq!(summary.total_received_sats, 100000);
        assert_eq!(summary.total_sent_sats, 50000);
    }

    #[test]
    fn test_export_csv() {
        let mut history = TransactionHistory::new();
        history.add_transaction(create_test_tx(100000, TransactionType::Received));

        let csv = history.export_csv(None);
        assert!(csv.contains("Txid"));
        assert!(csv.contains("100000"));
    }

    #[test]
    fn test_address_reuse_detection() {
        let mut history = TransactionHistory::new();

        let mut tx1 = create_test_tx(100000, TransactionType::Received);
        tx1.txid = Txid::from_byte_array([1; 32]);
        tx1.addresses = vec!["bc1qtest".to_string()];

        let mut tx2 = create_test_tx(50000, TransactionType::Received);
        tx2.txid = Txid::from_byte_array([2; 32]);
        tx2.addresses = vec!["bc1qtest".to_string()];

        history.add_transaction(tx1);
        history.add_transaction(tx2);

        let reuse = history.detect_address_reuse();
        assert_eq!(reuse.len(), 1);
        assert_eq!(reuse[0].usage_count, 2);
    }
}