kaccy-bitcoin 0.1.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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# kaccy-bitcoin Architecture

This document provides an architectural overview of the `kaccy-bitcoin` crate, including sequence diagrams for key flows, component interaction diagrams, and state machine diagrams.

## Table of Contents

1. [System Overview]#system-overview
2. [Core Components]#core-components
3. [Sequence Diagrams]#sequence-diagrams
4. [Component Interaction Diagrams]#component-interaction-diagrams
5. [State Machine Diagrams]#state-machine-diagrams
6. [Data Flow]#data-flow
7. [Integration Points]#integration-points

---

## System Overview

The `kaccy-bitcoin` crate provides comprehensive Bitcoin integration for the Kaccy Protocol, including:

- **Bitcoin Core RPC Client**: Direct communication with Bitcoin Core nodes
- **HD Wallet Management**: BIP32/BIP44/BIP84 hierarchical deterministic wallets
- **Payment Monitoring**: Real-time transaction tracking and confirmation monitoring
- **Lightning Network**: LND integration for instant payments
- **Advanced Features**: Multi-signature, PSBT, Taproot, CoinJoin, Atomic Swaps, DLCs
- **Security**: Transaction limits, activity monitoring, hardware wallet integration
- **Performance**: Connection pooling, caching, batch optimization

### Architecture Layers

```
┌─────────────────────────────────────────────────────────────────┐
│                     Application Layer                            │
│  (Kaccy Protocol API - uses kaccy-bitcoin as dependency)        │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│                   kaccy-bitcoin Crate                            │
│ ┌─────────────┬─────────────┬──────────────┬──────────────┐    │
│ │  Payment    │  Wallet     │  Transaction │  Security    │    │
│ │  Monitoring │  Management │  Management  │  & Limits    │    │
│ └─────────────┴─────────────┴──────────────┴──────────────┘    │
│ ┌─────────────┬─────────────┬──────────────┬──────────────┐    │
│ │  Lightning  │  Advanced   │  Observability│  Integration│    │
│ │  Network    │  Features   │  & Metrics   │  (L2/Privacy)│    │
│ └─────────────┴─────────────┴──────────────┴──────────────┘    │
│                    Core Infrastructure                           │
│ ┌─────────────────────────────────────────────────────────┐    │
│ │  Bitcoin RPC Client + Connection Pool + Caching         │    │
│ └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│              External Services                                   │
│  ┌──────────────┬──────────────┬──────────────┬─────────────┐  │
│  │ Bitcoin Core │     LND      │  Stacks/RSK  │   Hardware  │  │
│  │     RPC      │    (REST)    │   (L2 APIs)  │   Wallets   │  │
│  └──────────────┴──────────────┴──────────────┴─────────────┘  │
└─────────────────────────────────────────────────────────────────┘
```

---

## Core Components

### 1. Bitcoin Client (`client.rs`)
- **Purpose**: Low-level Bitcoin Core RPC communication
- **Key Features**:
  - Automatic reconnection with exponential backoff
  - Network info, block queries, transaction retrieval
  - Mempool monitoring, fee estimation
- **Dependencies**: `reqwest` for HTTP RPC calls

### 2. HD Wallet (`hd_wallet.rs`)
- **Purpose**: BIP84 (native SegWit) address derivation
- **Key Features**:
  - XPUB-based address generation
  - External (receiving) and internal (change) chains
  - Address caching for performance
- **Dependencies**: `bitcoin::bip32` for derivation

### 3. Payment Monitor (`monitor.rs`)
- **Purpose**: Poll Bitcoin Core for incoming transactions
- **Key Features**:
  - Configurable polling interval (default: 30 seconds)
  - Match transactions to orders via address
  - Amount validation (exact, underpaid, overpaid)
- **Dependencies**: `BitcoinClient`, `TransactionMatcher`, `ConfirmationTracker`

### 4. Transaction Matcher (`matcher.rs`)
- **Purpose**: Match incoming transactions to expected payments
- **Key Features**:
  - Address-based matching
  - Amount comparison with tolerance
  - Match status tracking

### 5. Confirmation Tracker (`confirmation.rs`)
- **Purpose**: Track confirmation levels and emit events
- **Key Features**:
  - Configurable confirmation thresholds (1, 3, 6 confirmations)
  - Event emission for state changes
  - Statistics tracking

### 6. PSBT Manager (`psbt.rs`)
- **Purpose**: Create and manage Partially Signed Bitcoin Transactions
- **Key Features**:
  - Withdrawal transaction creation
  - Hardware wallet signing support
  - Batch withdrawals
  - Fee estimation integration

### 7. Multi-Signature (`multisig.rs`)
- **Purpose**: M-of-N multi-signature wallet management
- **Key Features**:
  - P2WSH native SegWit multisig
  - PSBT-based signing coordination
  - Tiered custody management

### 8. Lightning Network (`lightning.rs`)
- **Purpose**: LND integration for instant payments
- **Key Features**:
  - Invoice generation and monitoring
  - Channel management
  - Payment tracking

### 9. Transaction Manager (`transaction_manager.rs`)
- **Purpose**: High-level transaction orchestration
- **Key Features**:
  - Integrates limits, UTXO selection, activity monitoring
  - Transaction validation and analytics
  - Consolidation recommendations

### 10. Activity Monitor (`activity_monitor.rs`)
- **Purpose**: Detect suspicious transaction patterns
- **Key Features**:
  - Risk scoring (0-100)
  - Velocity limits
  - Alert broadcasting for anomalies

---

## Sequence Diagrams

### 1. Payment Processing Flow

```
User → API → PaymentMonitor → BitcoinClient → Bitcoin Core
                ↓                    ↓
         TransactionMatcher    ConfirmationTracker
                ↓                    ↓
         AdminNotification      EventEmitter
                ↓                    ↓
           Database              WebSocket

Detailed Flow:
1. User sends BTC to generated address
2. PaymentMonitor polls Bitcoin Core every 30s via list_since_block
3. TransactionMatcher identifies transaction by address
4. TransactionMatcher validates amount (exact/underpaid/overpaid)
5. ConfirmationTracker monitors confirmations (0 → 1 → 3 → 6+)
6. Events emitted at each confirmation level
7. Admin notified of discrepancies
8. Order status updated in database
```

#### Sequence Diagram (ASCII):

```
┌──────┐  ┌─────┐  ┌────────────┐  ┌──────────┐  ┌───────────┐
│ User │  │ API │  │   Monitor  │  │  Client  │  │ Bitcoin   │
│      │  │     │  │            │  │          │  │   Core    │
└──┬───┘  └──┬──┘  └─────┬──────┘  └────┬─────┘  └─────┬─────┘
   │         │            │              │              │
   │ Pay BTC │            │              │              │
   ├─────────>            │              │              │
   │         │            │              │              │
   │         │  Poll (30s)│              │              │
   │         │<───────────┤              │              │
   │         │            │ list_since_block()          │
   │         │            ├──────────────>              │
   │         │            │              ├──────────────>
   │         │            │              │ transactions │
   │         │            │              <──────────────┤
   │         │            │ transactions │              │
   │         │            <──────────────┤              │
   │         │            │              │              │
   │         │  Match TX  │              │              │
   │         │<───────────┤              │              │
   │         │            │              │              │
   │         │ Confirm 1  │              │              │
   │         │<───────────┤              │              │
   │         │            │              │              │
   │         │ Confirm 6  │              │              │
   │         │<───────────┤              │              │
   │         │            │              │              │
   │ Updated │            │              │              │
   <─────────┤            │              │              │
   │         │            │              │              │
```

### 2. HD Wallet Address Generation

```
API → HdWallet → DerivationPath → AddressCache → Bitcoin Address

Detailed Flow:
1. API requests new address for order
2. HdWallet derives path: m/84'/0'/0'/0/{index}
3. Check AddressCache for existing address
4. If not cached, derive from XPUB
5. Generate P2WPKH (Bech32) address
6. Store in cache with order ID
7. Return address to API
```

#### Sequence Diagram (ASCII):

```
┌─────┐  ┌──────────┐  ┌──────────┐  ┌───────┐
│ API │  │ HdWallet │  │   Cache  │  │  BTC  │
└──┬──┘  └────┬─────┘  └────┬─────┘  └───┬───┘
   │          │              │            │
   │ get_address(order_id)   │            │
   ├──────────>              │            │
   │          │ check_cache  │            │
   │          ├──────────────>            │
   │          │     None     │            │
   <──────────────┤            │
   │          │              │            │
   │          │ derive(m/84'/0'/0'/0/N)  │
   │          ├──────────────────────────>│
   │          │         address          │
   <──────────────────────────┤
   │          │              │            │
   │          │ store(addr)  │            │
   │          ├──────────────>            │
   │          │      OK      │            │
   <──────────────┤            │
   │  address │              │            │
   <──────────┤              │            │
   │          │              │            │
```

### 3. Withdrawal Transaction Flow (PSBT)

```
User → API → TransactionManager → PsbtManager → HardwareWallet
                ↓                      ↓
         ActivityMonitor          UtxoManager
                ↓                      ↓
          LimitEnforcer           FeeEstimation
                ↓                      ↓
            Database              BitcoinClient

Detailed Flow:
1. User requests withdrawal
2. TransactionManager validates limits
3. ActivityMonitor checks for suspicious patterns
4. UtxoManager selects optimal inputs
5. FeeEstimation calculates appropriate fee
6. PsbtManager creates unsigned PSBT
7. PSBT sent to hardware wallet for signing
8. Signed PSBT returned and finalized
9. Transaction broadcast to Bitcoin network
10. Update database with txid
```

#### Sequence Diagram (ASCII):

```
┌──────┐ ┌─────┐ ┌─────────┐ ┌──────┐ ┌─────┐ ┌──────┐
│ User │ │ API │ │ TxMgr   │ │ PSBT │ │ HWI │ │  BTC │
└──┬───┘ └──┬──┘ └────┬────┘ └───┬──┘ └──┬──┘ └───┬──┘
   │        │         │          │       │        │
   │ Withdraw         │          │       │        │
   ├────────>         │          │       │        │
   │        │ validate│          │       │        │
   │        ├─────────>          │       │        │
   │        │   OK    │          │       │        │
   <─────────┤          │       │        │
   │        │         │ create_psbt      │        │
   │        │         ├──────────>       │        │
   │        │         │  unsigned        │        │
   │        │         <──────────┤       │        │
   │        │         │          │ sign  │        │
   │        │         ├──────────────────>        │
   │        │         │          │ signed│        │
   │        │         <──────────────────┤        │
   │        │         │ finalize │       │        │
   │        │         ├──────────>       │        │
   │        │         │  tx      │       │        │
   │        │         <──────────┤       │        │
   │        │         │          │broadcast       │
   │        │         ├────────────────────────────>
   │        │         │          │       │  txid  │
   │        │         <────────────────────────────┤
   │  txid  │         │          │       │        │
   <────────┤         │          │       │        │
   │        │         │          │       │        │
```

### 4. Lightning Invoice Payment Flow

```
User → API → LightningPaymentManager → LndClient → LND
                                    InvoiceMonitor
                                       EventEmitter
                                        Database

Detailed Flow:
1. User requests Lightning invoice
2. LightningPaymentManager creates invoice via LND
3. Invoice returned to user with payment request
4. User pays invoice
5. InvoiceMonitor polls LND for status updates
6. Payment detected (settled/expired)
7. Event emitted with payment status
8. Order updated in database
```

### 5. Atomic Swap Flow

```
Initiator → SwapManager → HTLCManager → BitcoinClient
                ↓               ↓
         Participant      PreimageStore
                ↓               ↓
           SwapTracker    TimelockMonitor

Detailed Flow:
1. Initiator creates swap with payment hash
2. HTLCManager creates HTLC script with timelock
3. Initiator funds HTLC address
4. Participant responds and creates reciprocal HTLC
5. Participant funds their HTLC
6. Initiator claims participant's HTLC (reveals preimage)
7. Participant learns preimage from blockchain
8. Participant claims initiator's HTLC
9. Swap completed successfully
10. If timeout: refund paths activated
```

### 6. Multi-Signature Transaction Flow

```
Platform → MultisigManager → SignatureCoordinator → Signers (Platform/User/Cold)
                ↓                    ↓
          PsbtBuilder          BitcoinClient
                ↓                    ↓
           Database            Bitcoin Core

Detailed Flow:
1. Platform initiates multisig transaction (e.g., 2-of-3)
2. MultisigManager creates PSBT
3. SignatureCoordinator collects signatures from required parties
4. Platform signs with hot key
5. User signs with their key (or hardware wallet)
6. Once threshold met (2 signatures), finalize transaction
7. Broadcast to Bitcoin network
8. Update database with transaction details
```

---

## Component Interaction Diagrams

### 1. Payment Monitoring System

```
┌─────────────────────────────────────────────────────────────┐
│                   Payment Monitoring System                  │
│                                                              │
│  ┌──────────────┐         ┌──────────────┐                 │
│  │   Monitor    │◄────────┤   Config     │                 │
│  │   (Poller)   │         │ (30s interval)│                 │
│  └───────┬──────┘         └──────────────┘                 │
│          │                                                   │
│          ├──────────┐                                       │
│          │          │                                       │
│          ▼          ▼                                       │
│  ┌──────────┐  ┌──────────┐      ┌─────────────┐          │
│  │ Bitcoin  │  │Transaction│◄─────┤   Address   │          │
│  │  Client  │  │  Matcher  │      │    Book     │          │
│  └──────────┘  └─────┬────┘      └─────────────┘          │
│                      │                                      │
│                      ▼                                      │
│            ┌──────────────────┐                            │
│            │ Confirmation     │                            │
│            │   Tracker        │                            │
│            └────────┬─────────┘                            │
│                     │                                      │
│          ┌──────────┼──────────┐                          │
│          ▼          ▼           ▼                          │
│   ┌──────────┐ ┌────────┐ ┌─────────┐                    │
│   │  Event   │ │ Notify │ │  Stats  │                    │
│   │ Emitter  │ │ Service│ │ Tracker │                    │
│   └──────────┘ └────────┘ └─────────┘                    │
└─────────────────────────────────────────────────────────────┘
```

### 2. Transaction Management System

```
┌─────────────────────────────────────────────────────────────┐
│               Transaction Management System                  │
│                                                              │
│              ┌─────────────────┐                            │
│              │  Transaction    │                            │
│              │    Manager      │                            │
│              └────────┬────────┘                            │
│                       │                                      │
│      ┌────────────────┼────────────────┐                   │
│      │                │                │                   │
│      ▼                ▼                ▼                   │
│ ┌─────────┐    ┌──────────┐    ┌──────────┐              │
│ │  Limit  │    │ Activity │    │   UTXO   │              │
│ │Enforcer │    │ Monitor  │    │ Manager  │              │
│ └────┬────┘    └─────┬────┘    └─────┬────┘              │
│      │               │               │                    │
│      │               ▼               │                    │
│      │         ┌──────────┐          │                    │
│      │         │   Risk   │          │                    │
│      │         │  Scorer  │          │                    │
│      │         └──────────┘          │                    │
│      │                               │                    │
│      └───────────┬───────────────────┘                    │
│                  │                                         │
│                  ▼                                         │
│          ┌──────────────┐                                 │
│          │    PSBT      │                                 │
│          │   Manager    │                                 │
│          └──────┬───────┘                                 │
│                 │                                          │
│                 ▼                                          │
│         ┌──────────────┐                                  │
│         │   Bitcoin    │                                  │
│         │    Client    │                                  │
│         └──────────────┘                                  │
└─────────────────────────────────────────────────────────────┘
```

### 3. HD Wallet System

```
┌─────────────────────────────────────────────────────────────┐
│                    HD Wallet System                          │
│                                                              │
│              ┌─────────────┐                                │
│              │  HdWallet   │                                │
│              └──────┬──────┘                                │
│                     │                                        │
│          ┌──────────┼──────────┐                           │
│          │          │          │                           │
│          ▼          ▼          ▼                           │
│   ┌──────────┐ ┌────────┐ ┌──────────┐                   │
│   │   XPUB   │ │Derivat-│ │ Address  │                   │
│   │ Validator│ │  ion   │ │  Cache   │                   │
│   └──────────┘ │ Engine │ └──────────┘                   │
│                └────┬───┘                                  │
│                     │                                      │
│          ┌──────────┼──────────┐                          │
│          │          │          │                          │
│          ▼          ▼          ▼                          │
│   ┌──────────┐ ┌────────┐ ┌──────────┐                  │
│   │ External │ │Internal│ │   Gap    │                  │
│   │  Chain   │ │ Chain  │ │  Limit   │                  │
│   │(Receive) │ │(Change)│ │ Tracker  │                  │
│   └──────────┘ └────────┘ └──────────┘                  │
│                     │                                     │
│                     ▼                                     │
│            ┌────────────────┐                            │
│            │  Address Book  │                            │
│            │ (Label mapping)│                            │
│            └────────────────┘                            │
└─────────────────────────────────────────────────────────────┘
```

### 4. Security & Monitoring System

```
┌─────────────────────────────────────────────────────────────┐
│              Security & Monitoring System                    │
│                                                              │
│          ┌──────────────────────┐                          │
│          │  Activity Monitor    │                          │
│          └──────────┬───────────┘                          │
│                     │                                       │
│          ┌──────────┼──────────┐                           │
│          │          │          │                           │
│          ▼          ▼          ▼                           │
│   ┌──────────┐ ┌────────┐ ┌──────────┐                   │
│   │ Velocity │ │  Large │ │  Rapid   │                   │
│   │  Checker │ │   TX   │ │Succession│                   │
│   └──────────┘ │Detector│ └──────────┘                   │
│                └────────┘                                  │
│                     │                                      │
│                     ▼                                      │
│            ┌────────────────┐                             │
│            │  Risk Scorer   │                             │
│            │    (0-100)     │                             │
│            └────────┬───────┘                             │
│                     │                                      │
│          ┌──────────┼──────────┐                          │
│          │          │          │                          │
│          ▼          ▼          ▼                          │
│   ┌──────────┐ ┌────────┐ ┌──────────┐                  │
│   │  Alert   │ │  Audit │ │  Metrics │                  │
│   │Broadcast │ │ Logger │ │Collector │                  │
│   └──────────┘ └────────┘ └──────────┘                  │
│                     │                                     │
│                     ▼                                     │
│              ┌────────────┐                              │
│              │ Tx Limits  │                              │
│              │  Enforcer  │                              │
│              └────────────┘                              │
└─────────────────────────────────────────────────────────────┘
```

### 5. Infrastructure Layer

```
┌─────────────────────────────────────────────────────────────┐
│                 Infrastructure Layer                         │
│                                                              │
│              ┌─────────────────┐                            │
│              │ Bitcoin Client  │                            │
│              └────────┬────────┘                            │
│                       │                                      │
│          ┌────────────┼────────────┐                        │
│          │            │            │                        │
│          ▼            ▼            ▼                        │
│   ┌──────────┐ ┌──────────┐ ┌──────────┐                  │
│   │Connection│ │  Cache   │ │ Metrics  │                  │
│   │   Pool   │ │ Manager  │ │ Tracker  │                  │
│   └─────┬────┘ └─────┬────┘ └──────────┘                  │
│         │            │                                      │
│         │      ┌─────┼─────┐                               │
│         │      │     │     │                               │
│         │      ▼     ▼     ▼                               │
│         │   ┌────┐┌────┐┌────┐                            │
│         │   │ TX ││UTXO││Block│                           │
│         │   │Cache││Cache││Cache│                         │
│         │   └────┘└────┘└────┘                            │
│         │                                                  │
│         ▼                                                  │
│  ┌──────────────┐                                         │
│  │Health Monitor│                                         │
│  │& Auto-Retry  │                                         │
│  └──────┬───────┘                                         │
│         │                                                  │
│         ▼                                                  │
│  ┌──────────────┐                                         │
│  │ Structured   │                                         │
│  │   Logging    │                                         │
│  └──────────────┘                                         │
└─────────────────────────────────────────────────────────────┘
```

---

## State Machine Diagrams

### 1. Payment Status State Machine

```
                    ┌──────────────┐
                    │   PENDING    │ (Initial state: address generated)
                    └──────┬───────┘
                                         Transaction  │  received in mempool
                 detected  │
                                               ┌──────────────┐
                    │ UNCONFIRMED  │ (0 confirmations)
                    └──────┬───────┘
                                             1 block  │  mined
                confirmed  │
                                               ┌──────────────┐
         ┌──────────┤  CONFIRMED   │ (1-2 confirmations)
         │          └──────┬───────┘
         │                 │
         │        3 blocks │  mined
         │      confirmed  │
         │                 ▼
         │          ┌──────────────┐
         │          │FULL_CONFIRMED│ (3-5 confirmations)
         │          └──────┬───────┘
         │                 │
         │        6 blocks │  mined
         │      confirmed  │
         │                 ▼
         │          ┌──────────────┐
         │          │   FINALIZED  │ (6+ confirmations)
         │          └──────────────┘
                  │ (Any state can transition to FAILED)
                  └─────────►┌──────────────┐
                    │    FAILED    │ (Error/timeout/invalid)
                    └──────────────┘

State Transitions:
- PENDING → UNCONFIRMED: Transaction detected in mempool
- UNCONFIRMED → CONFIRMED: First block confirmation
- CONFIRMED → FULL_CONFIRMED: Third block confirmation
- FULL_CONFIRMED → FINALIZED: Sixth block confirmation
- Any → FAILED: Error, timeout, or invalid transaction
```

### 2. Lightning Invoice State Machine

```
                    ┌──────────────┐
                    │     OPEN     │ (Invoice created, awaiting payment)
                    └──────┬───────┘
                                         ┌────────────┼────────────┐
              │            │            │
     Payment  │   Timeout  │   Payment  │
     received │  exceeded  │  in flight │
              │            │            │
              ▼            ▼            ▼
       ┌──────────┐ ┌──────────┐ ┌──────────┐
       │ SETTLED  │ │ EXPIRED  │ │  PENDING │
       └──────────┘ └──────────┘ └────┬─────┘
                                                                  ┌───────────┼───────────┐
                           │                       │
                  Payment  │              Payment  │
                 completed │               failed  │
                           │                       │
                           ▼                       ▼
                    ┌──────────┐           ┌──────────┐
                    │ SETTLED  │           │ EXPIRED  │
                    └──────────┘           └──────────┘

State Transitions:
- OPEN → PENDING: HTLC received, payment in flight
- OPEN → EXPIRED: Timeout exceeded without payment
- PENDING → SETTLED: HTLC successfully settled
- PENDING → EXPIRED: HTLC failed or timeout
```

### 3. Atomic Swap State Machine

```
                    ┌──────────────┐
                    │  INITIATED   │ (Initiator creates swap)
                    └──────┬───────┘
                                       Participant    │  accepts swap
                 responds  │
                                               ┌──────────────┐
         ┌──────────┤    LOCKED    │ (Both parties funded HTLCs)
         │          └──────┬───────┘
         │                 │
         │      Initiator  │  claims with preimage
         │         claims  │
         │                 ▼
         │          ┌──────────────┐
         │          │  COMPLETED   │ (Successful swap)
         │          └──────────────┘
                  │ (Alternative paths)
                  ├─────────►┌──────────────┐
         │          │   REFUNDED   │ (Timeout, refund activated)
         │          └──────────────┘
                  └─────────►┌──────────────┐
                    │  CANCELLED   │ (Cancelled before lock)
                    └──────────────┘

State Transitions:
- INITIATED → LOCKED: Both HTLCs funded
- INITIATED → CANCELLED: Swap cancelled before funding
- LOCKED → COMPLETED: Initiator claims, revealing preimage
- LOCKED → REFUNDED: Timeout exceeded, refund paths activated
```

### 4. PSBT (Transaction Signing) State Machine

```
                    ┌──────────────┐
                    │   CREATED    │ (Unsigned PSBT created)
                    └──────┬───────┘
                                       First signer   │  adds signature
               signs PSBT  │
                                               ┌──────────────┐
                    │PARTIALLY_SIGN│ (1+ signatures, needs more)
                    └──────┬───────┘
                                     Threshold met    │  (e.g., 2-of-3)
          (all required    │
           signatures)     │
                                               ┌──────────────┐
         ┌──────────┤   SIGNED     │ (All required signatures present)
         │          └──────┬───────┘
         │                 │
         │      Finalize   │  and extract transaction
         │        PSBT     │
         │                 ▼
         │          ┌──────────────┐
         │          │  FINALIZED   │ (Ready to broadcast)
         │          └──────┬───────┘
         │                 │
         │     Broadcast   │  to network
         │  to Bitcoin Core│
         │                 ▼
         │          ┌──────────────┐
         │          │  BROADCAST   │ (Transaction in mempool/blockchain)
         │          └──────────────┘
                  │ (Error path)
                  └─────────►┌──────────────┐
                    │   REJECTED   │ (Invalid/rejected)
                    └──────────────┘

State Transitions:
- CREATED → PARTIALLY_SIGN: First signature added
- PARTIALLY_SIGN → PARTIALLY_SIGN: Additional signatures (not yet threshold)
- PARTIALLY_SIGN → SIGNED: Threshold met
- SIGNED → FINALIZED: PSBT finalized and transaction extracted
- FINALIZED → BROADCAST: Transaction broadcast to network
- Any → REJECTED: Validation failure or rejection
```

### 5. UTXO Consolidation State Machine

```
                    ┌──────────────┐
                    │     IDLE     │ (No consolidation needed)
                    └──────┬───────┘
                                   High UTXO count    │  OR low fee environment
           detected        │  triggers consolidation
                                               ┌──────────────┐
                    │  ANALYZING   │ (Checking UTXOs and fees)
                    └──────┬───────┘
                                      Plan created    │  with optimal inputs
                                               ┌──────────────┐
         ┌──────────┤   PLANNED    │ (Consolidation plan ready)
         │          └──────┬───────┘
         │                 │
         │    Transaction  │  built and signed
         │        created  │
         │                 ▼
         │          ┌──────────────┐
         │          │ CONSOLIDATING│ (Transaction broadcast)
         │          └──────┬───────┘
         │                 │
         │    Transaction  │  confirmed
         │      confirmed  │
         │                 ▼
         │          ┌──────────────┐
         │          │  COMPLETED   │ (UTXOs consolidated)
         │          └──────────────┘
         │                 │
         │                 │  Return to monitoring
         │                 ▼
         │          ┌──────────────┐
         └─────────►│     IDLE     │
                    └──────────────┘

State Transitions:
- IDLE → ANALYZING: Consolidation trigger detected
- ANALYZING → PLANNED: Plan created successfully
- PLANNED → CONSOLIDATING: Transaction broadcast
- CONSOLIDATING → COMPLETED: Transaction confirmed
- COMPLETED → IDLE: Return to monitoring
```

---

## Data Flow

### 1. Incoming Payment Data Flow

```
Bitcoin Network
            Bitcoin Core RPC
            BitcoinClient (kaccy-bitcoin)
            PaymentMonitor (polling every 30s)
            ├──► TransactionMatcher (match by address)
      │         │
      │         ▼
      │    MatchStatus (Exact/Underpaid/Overpaid)
            ├──► ConfirmationTracker (track 0→1→3→6)
      │         │
      │         ▼
      │    ConfirmationEvents
            ├──► AdminNotificationService (if discrepancy)
            └──► EventEmitter
                                ├──► WebSocket (real-time updates)
                                └──► Database (order status update)
```

### 2. Outgoing Payment Data Flow

```
User Request (Withdrawal)
            API (kaccy-api)
            TransactionManager (kaccy-bitcoin)
            ├──► LimitEnforcer (check daily/monthly limits)
            ├──► ActivityMonitor (check risk score)
            └──► UtxoManager (select optimal inputs)
                              PsbtManager (create unsigned PSBT)
                              HardwareWallet / Signer (sign PSBT)
                              PsbtManager (finalize PSBT)
                              BitcoinClient (broadcast transaction)
                              Bitcoin Core RPC
                              Bitcoin Network
```

### 3. Address Generation Data Flow

```
Order Created (kaccy-api)
            HdWallet.get_new_address(order_id)
            ├──► AddressCache.check(order_id)
      │         │
      │         ▼
      │    Cache Miss
            ├──► DerivationPath.derive(m/84'/0'/0'/0/{index})
      │         │
      │         ▼
      │    BIP32 Derivation
      │         │
      │         ▼
      │    P2WPKH Address (Bech32)
            ├──► AddressCache.store(order_id, address)
            └──► AddressBook.map(order_id, address, label)
                              Return address to API
```

---

## Integration Points

### 1. External Service Integrations

#### Bitcoin Core (RPC)
- **Protocol**: JSON-RPC over HTTP
- **Authentication**: Basic auth (username/password)
- **Key Methods**:
  - `getnetworkinfo`: Network status
  - `listsinceblock`: List transactions since block
  - `sendrawtransaction`: Broadcast transaction
  - `estimatesmartfee`: Fee estimation
  - `getmempoolinfo`: Mempool status

#### LND (Lightning Network Daemon)
- **Protocol**: REST API
- **Authentication**: Macaroon-based
- **Key Endpoints**:
  - `POST /v1/invoices`: Create invoice
  - `GET /v1/invoice/{r_hash}`: Lookup invoice
  - `GET /v1/channels`: List channels
  - `POST /v1/channels`: Open channel

#### Stacks (L2)
- **Protocol**: HTTP REST API
- **Key Operations**:
  - Deploy Clarity smart contracts
  - Monitor bridge transactions
  - Track token transfers

#### RSK (L2)
- **Protocol**: Ethereum-compatible JSON-RPC
- **Key Operations**:
  - Peg-in (BTC → rBTC)
  - Peg-out (rBTC → BTC)
  - Smart contract deployment

### 2. Internal Integrations (Kaccy Ecosystem)

#### kaccy-db
- **Purpose**: Persistent storage for orders, transactions, users
- **Key Functions**:
  - `update_btc_txid`: Link transaction to order
  - `get_order_by_address`: Retrieve order by payment address
  - `update_order_status`: Update payment status

#### kaccy-api
- **Purpose**: REST API serving user requests
- **Key Functions**:
  - Order creation (triggers address generation)
  - Withdrawal requests (triggers PSBT creation)
  - WebSocket notifications (payment updates)

#### kaccy-core
- **Purpose**: Core business logic
- **Key Functions**:
  - Event bus integration
  - Pricing calculations
  - Trading logic

### 3. Hardware Wallet Integration (HWI)

#### Supported Devices
- **Ledger**: Via HID/USB
- **Trezor**: Via HID/USB
- **Generic**: Via Bitcoin Core HWI tool

#### Key Operations
- PSBT signing
- Address verification
- Multi-signature coordination

### 4. Observability Integrations

#### Metrics (Prometheus)
- Transaction volume counters
- Fee estimation gauges
- RPC call latency histograms
- Confirmation time tracking

#### Logging (Structured)
- Correlation IDs for request tracing
- Performance spans
- RPC request/response logging

#### Health Checks
- Bitcoin Core connectivity
- LND connectivity
- Connection pool health
- Cache hit rates

---

## Architectural Decisions

### 1. Polling vs. WebSocket for Bitcoin Core
- **Decision**: Polling (30-second interval)
- **Rationale**:
  - Bitcoin Core RPC doesn't provide native WebSocket/streaming
  - ZMQ available but adds complexity
  - 30s polling provides acceptable latency for on-chain payments
  - Simpler error handling and reconnection logic

### 2. PSBT for Transaction Signing
- **Decision**: Use PSBT (BIP 174) for all transaction signing
- **Rationale**:
  - Hardware wallet compatibility
  - Multi-signature support
  - External signing workflows (air-gapped)
  - Industry standard

### 3. BIP84 (Native SegWit) for Address Generation
- **Decision**: Use BIP84 (P2WPKH) as default address type
- **Rationale**:
  - Lower transaction fees (SegWit)
  - Widely supported across wallets
  - Enhanced security (malleability fix)
  - Future-proof for Taproot migration

### 4. Connection Pooling for Bitcoin RPC
- **Decision**: Implement connection pool with health monitoring
- **Rationale**:
  - High concurrency support
  - Reduced connection overhead
  - Automatic failover
  - Better resource utilization

### 5. Tiered Caching Strategy
- **Decision**: Multi-level cache (transactions, UTXOs, blocks)
- **Rationale**:
  - Reduce RPC calls to Bitcoin Core
  - Improve response times
  - TTL-based invalidation prevents stale data
  - Configurable per use case

---

## Security Considerations

### 1. Key Management
- **XPUB-only** for address generation (no private keys in server)
- Hardware wallet integration for signing
- Multi-signature for high-value transactions
- Key rotation policies

### 2. Transaction Limits
- Per-user daily/monthly limits
- Platform-wide limits
- Single transaction maximum
- Velocity limits (amount per hour)

### 3. Activity Monitoring
- Risk scoring (0-100) for transactions
- Large transaction alerts
- Rapid succession detection
- Admin notifications for anomalies

### 4. Audit Logging
- Immutable audit trail
- All transaction operations logged
- Compliance reporting
- Query capabilities for investigations

### 5. Network Security
- TLS for all RPC connections
- Macaroon authentication for LND
- IP whitelisting support
- Rate limiting

---

## Performance Optimizations

### 1. Caching
- Transaction cache (1-hour TTL)
- UTXO cache (invalidated on spend)
- Block header cache (immutable)
- Address cache (persistent)

### 2. Batch Processing
- Batch withdrawals (multiple outputs in single transaction)
- UTXO consolidation during low-fee periods
- Batch RBF operations

### 3. Connection Management
- Connection pooling (reuse connections)
- Health monitoring (automatic reconnection)
- Concurrent request handling

### 4. UTXO Management
- Optimal coin selection algorithms
- Dust prevention
- Consolidation automation
- Branch-and-bound selection

---

## Future Architecture Considerations

### 1. Horizontal Scaling
- Stateless design for multiple instances
- Shared cache (Redis) for distributed deployments
- Load balancing across Bitcoin Core nodes

### 2. Event-Driven Architecture
- Migrate to event bus for all state changes
- Async processing for non-critical paths
- Event sourcing for audit trail

### 3. Microservices Separation
- Separate payment monitoring service
- Dedicated Lightning service
- Independent transaction signing service

### 4. Enhanced Privacy
- CoinJoin integration by default
- PayJoin for all payments
- Tor support for RPC connections

---

## Conclusion

The `kaccy-bitcoin` crate provides a comprehensive, production-ready Bitcoin integration with:
- **Robust payment monitoring** with confirmation tracking
- **Flexible wallet management** via BIP84 HD wallets
- **Advanced transaction handling** with PSBT, multi-sig, Taproot
- **Security-first design** with limits, monitoring, and audit logging
- **Performance optimizations** via caching, pooling, and batch processing
- **Lightning Network integration** for instant payments
- **L2 support** for Stacks and RSK
- **Privacy features** like CoinJoin, PayJoin, and atomic swaps

This architecture is designed to scale from MVP to production while maintaining security, reliability, and performance.