blvm-node 0.1.51

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
//! Mining coordinator
//!
//! Handles block mining, template generation, and mining coordination.

use crate::utils::current_timestamp;
use anyhow::Result;
use blvm_protocol::segwit::Witness;
use blvm_protocol::{Block, BlockHeader, Transaction};
use std::collections::HashMap;
use tracing::{debug, info, warn};

/// Mempool provider trait for dependency injection
pub trait MempoolProvider: Send + Sync {
    /// Get transactions from mempool
    fn get_transactions(&self) -> Vec<Transaction>;

    /// Get transaction by hash
    fn get_transaction(&self, hash: &[u8; 32]) -> Option<Transaction>;

    /// Get mempool size
    fn get_mempool_size(&self) -> usize;

    /// Get prioritized transactions (by fee rate)
    /// Requires UTXO set for accurate fee calculation
    fn get_prioritized_transactions(
        &self,
        limit: usize,
        utxo_set: &blvm_protocol::UtxoSet,
    ) -> Vec<Transaction>;

    /// Remove transaction from mempool
    fn remove_transaction(&mut self, hash: &[u8; 32]) -> bool;

    /// SegWit witness stacks for a mempool transaction (one per input), if stored.
    fn get_transaction_witnesses(&self, hash: &[u8; 32]) -> Option<Vec<Witness>>;
}

/// Transaction selector for block building
pub struct TransactionSelector {
    /// Maximum block size
    max_block_size: usize,
    /// Maximum block weight
    max_block_weight: u64,
    /// Minimum fee rate (satoshis per vbyte)
    min_fee_rate: u64,
}

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

impl TransactionSelector {
    /// Create a new transaction selector
    pub fn new() -> Self {
        Self {
            max_block_size: 1_000_000,   // 1MB
            max_block_weight: 4_000_000, // 4M weight units
            min_fee_rate: 1,             // 1 satoshi per byte
        }
    }

    /// Create with custom parameters
    pub fn with_params(max_block_size: usize, max_block_weight: u64, min_fee_rate: u64) -> Self {
        Self {
            max_block_size,
            max_block_weight,
            min_fee_rate,
        }
    }

    /// Select transactions for block
    /// Note: Requires UTXO set for fee calculation - caller must provide it
    pub fn select_transactions(
        &self,
        mempool: &dyn MempoolProvider,
        utxo_set: &blvm_protocol::UtxoSet,
    ) -> Vec<Transaction> {
        let mut selected = Vec::new();
        let mut current_size = 0;
        let mut current_weight = 0;

        // Get prioritized transactions (with UTXO set for fee calculation)
        // MempoolManager.get_prioritized_transactions() already returns transactions
        // sorted by fee rate (descending) calculated with real UTXO set
        let transactions = mempool.get_prioritized_transactions(1000, utxo_set);

        for tx in transactions {
            use blvm_protocol::block::calculate_tx_id;
            let txid = calculate_tx_id(&tx);
            let input_witnesses = mempool.get_transaction_witnesses(&txid);
            let tx_stripped = blvm_consensus::transaction::calculate_transaction_size(&tx);
            let tx_weight = bip141_weight(&tx, input_witnesses.as_deref());
            let tx_vsize = transaction_vsize(&tx, input_witnesses.as_deref());

            // Check if adding this transaction would exceed limits
            if current_size + tx_stripped > self.max_block_size
                || current_weight + tx_weight > self.max_block_weight
            {
                break;
            }

            // Check minimum fee rate (sat/vB) using real UTXO set
            let fee_rate = self.calculate_fee_rate_with_utxo(&tx, utxo_set, tx_vsize);
            if fee_rate < self.min_fee_rate {
                continue;
            }

            selected.push(tx);
            current_size += tx_stripped;
            current_weight += tx_weight;
        }

        selected
    }

    /// Fee rate (sat/vB) using UTXO set and virtual size.
    fn calculate_fee_rate_with_utxo(
        &self,
        tx: &Transaction,
        utxo_set: &blvm_protocol::UtxoSet,
        tx_vsize: usize,
    ) -> u64 {
        if tx_vsize == 0 {
            return 0;
        }

        let mut input_total = 0u64;
        for input in &tx.inputs {
            if let Some(utxo) = utxo_set.get(&input.prevout) {
                input_total += utxo.value as u64;
            }
        }

        let output_total: u64 = tx.outputs.iter().map(|out| out.value as u64).sum();
        let fee = input_total.saturating_sub(output_total);

        fee / tx_vsize as u64
    }

    /// Get maximum block size
    pub fn max_block_size(&self) -> usize {
        self.max_block_size
    }

    /// Get maximum block weight
    pub fn max_block_weight(&self) -> u64 {
        self.max_block_weight
    }

    /// Get minimum fee rate
    pub fn min_fee_rate(&self) -> u64 {
        self.min_fee_rate
    }
}

/// BIP141 weight: 4 × stripped_size + total_size (witness bytes included in total).
fn bip141_weight(tx: &Transaction, input_witnesses: Option<&[Witness]>) -> u64 {
    let base = blvm_consensus::transaction::calculate_transaction_size(tx) as u64;
    let witness_bytes: u64 = input_witnesses
        .map(|wits| {
            wits.iter()
                .flat_map(|stack| stack.iter())
                .map(|elem| elem.len() as u64)
                .sum()
        })
        .unwrap_or(0);
    let total = base + witness_bytes;
    base.saturating_mul(4).saturating_add(total)
}

/// Virtual size (vbytes) from BIP141 weight.
fn transaction_vsize(tx: &Transaction, input_witnesses: Option<&[Witness]>) -> usize {
    use blvm_consensus::witness::weight_to_vsize;
    weight_to_vsize(bip141_weight(tx, input_witnesses)) as usize
}

/// Mining engine for block mining
pub struct MiningEngine {
    /// Mining enabled flag
    mining_enabled: bool,
    /// Mining threads
    mining_threads: u32,
    /// Current block template
    block_template: Option<Block>,
    /// Mining statistics
    stats: MiningStats,
}

#[derive(Debug, Clone)]
pub struct MiningStats {
    pub blocks_mined: u64,
    pub total_hashrate: f64,
    pub average_block_time: f64,
    pub last_block_time: Option<u64>,
}

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

impl MiningEngine {
    /// Create a new mining engine
    pub fn new() -> Self {
        Self {
            mining_enabled: false,
            mining_threads: 1,
            block_template: None,
            stats: MiningStats {
                blocks_mined: 0,
                total_hashrate: 0.0,
                average_block_time: 0.0,
                last_block_time: None,
            },
        }
    }

    /// Create with custom thread count
    pub fn with_threads(threads: u32) -> Self {
        Self {
            mining_enabled: false,
            mining_threads: threads,
            block_template: None,
            stats: MiningStats {
                blocks_mined: 0,
                total_hashrate: 0.0,
                average_block_time: 0.0,
                last_block_time: None,
            },
        }
    }

    /// Enable mining
    pub fn enable_mining(&mut self) {
        self.mining_enabled = true;
        info!("Mining enabled with {} threads", self.mining_threads);
    }

    /// Disable mining
    pub fn disable_mining(&mut self) {
        self.mining_enabled = false;
        info!("Mining disabled");
    }

    /// Check if mining is enabled
    pub fn is_mining_enabled(&self) -> bool {
        self.mining_enabled
    }

    /// Get mining statistics
    pub fn get_stats(&self) -> &MiningStats {
        &self.stats
    }

    /// Get mining threads
    pub fn get_threads(&self) -> u32 {
        self.mining_threads
    }

    /// Set mining threads
    pub fn set_threads(&mut self, threads: u32) {
        self.mining_threads = threads;
    }

    /// Mine a block template using actual proof of work (async, multithreaded)
    pub async fn mine_template(&mut self, template: Block) -> Result<Block> {
        debug!("Mining block template with {} threads", self.mining_threads);

        // Update template
        self.block_template = Some(template.clone());

        // Use consensus layer to mine the block (actual PoW)
        use blvm_protocol::ConsensusProof;
        let consensus = ConsensusProof::new();

        // Calculate max attempts per thread based on difficulty
        // For regtest: low difficulty, should find nonce quickly
        // For testnet/mainnet: high difficulty, may need many attempts
        let max_attempts_per_thread = 1_000_000u64; // Reasonable limit per thread

        // Multi-threaded mining: spawn tasks for each thread
        if self.mining_threads > 1 {
            self.mine_template_multithreaded(template, max_attempts_per_thread, &consensus)
                .await
        } else {
            // Single-threaded: use blocking task to avoid blocking async runtime
            let template_clone = template.clone();
            let (mined_block, result) = tokio::task::spawn_blocking(move || {
                consensus.mine_block(template_clone, max_attempts_per_thread)
            })
            .await
            .map_err(|e| anyhow::anyhow!("Mining task panicked: {}", e))?
            .map_err(|e| anyhow::anyhow!("Mining failed: {}", e))?;

            self.handle_mining_result(mined_block, result)
        }
    }

    /// Multi-threaded mining implementation
    async fn mine_template_multithreaded(
        &mut self,
        template: Block,
        max_attempts_per_thread: u64,
        _consensus: &blvm_protocol::ConsensusProof,
    ) -> Result<Block> {
        use blvm_protocol::mining::MiningResult;
        use blvm_protocol::pow::check_proof_of_work;
        use tokio::sync::oneshot;

        // Calculate nonce range per thread
        let nonces_per_thread = max_attempts_per_thread;
        let total_threads = self.mining_threads as u64;

        // Spawn mining tasks for each thread
        let mut handles = Vec::new();
        for thread_id in 0..total_threads {
            let template_clone = template.clone();
            let start_nonce = thread_id * nonces_per_thread;
            let end_nonce = start_nonce + nonces_per_thread;

            let (tx, rx) = oneshot::channel();

            // Spawn blocking task for CPU-bound mining work
            let handle = tokio::task::spawn_blocking(move || {
                // Try nonces in this thread's range
                for nonce in start_nonce..end_nonce {
                    let mut block = template_clone.clone();
                    block.header.nonce = nonce;

                    // Check proof of work using standalone function
                    if let Ok(valid) = check_proof_of_work(&block.header) {
                        if valid {
                            let _ = tx.send(Ok((block, MiningResult::Success)));
                            return;
                        }
                    }
                }

                // No valid nonce found in this range
                let mut block = template_clone;
                block.header.nonce = start_nonce; // Last nonce tried (failure result)
                let _ = tx.send(Ok((block, MiningResult::Failure)));
            });

            handles.push((handle, rx));
        }

        // Wait for first successful result or all failures
        let mut results = Vec::new();
        for (handle, rx) in handles {
            // Wait for task completion
            handle
                .await
                .map_err(|e| anyhow::anyhow!("Mining task panicked: {}", e))?;

            // Get result
            match rx.await {
                Ok(Ok((block, result))) => {
                    if matches!(result, MiningResult::Success) {
                        // Found valid nonce! Return immediately
                        return self.handle_mining_result(block, result);
                    }
                    results.push((block, result));
                }
                Ok(Err(e)) => return Err(e),
                Err(_) => {
                    // Channel closed, task may have found solution
                    continue;
                }
            }
        }

        // All threads failed
        if let Some((block, _)) = results.first() {
            self.handle_mining_result(block.clone(), MiningResult::Failure)
        } else {
            Err(anyhow::anyhow!("Mining failed: all threads exhausted"))
        }
    }

    /// Handle mining result and update statistics
    fn handle_mining_result(
        &mut self,
        mined_block: Block,
        result: blvm_protocol::mining::MiningResult,
    ) -> Result<Block> {
        use blvm_protocol::mining::MiningResult;

        match result {
            MiningResult::Success => {
                info!(
                    "Successfully mined block with nonce {}",
                    mined_block.header.nonce
                );

                // Update statistics
                self.stats.blocks_mined += 1;
                self.stats.last_block_time = Some(current_timestamp());

                Ok(mined_block)
            }
            MiningResult::Failure => {
                // Could not find valid nonce in max_attempts
                // This is normal for high difficulty (mainnet)
                warn!("Could not find valid nonce (difficulty may be too high)");
                Err(anyhow::anyhow!("Mining failed: could not find valid nonce"))
            }
        }
    }

    /// Get current block template
    pub fn get_block_template(&self) -> Option<&Block> {
        self.block_template.as_ref()
    }

    /// Clear block template
    pub fn clear_template(&mut self) {
        self.block_template = None;
    }

    /// Update hashrate
    pub fn update_hashrate(&mut self, hashrate: f64) {
        self.stats.total_hashrate = hashrate;
    }

    /// Update average block time
    pub fn update_average_block_time(&mut self, block_time: f64) {
        self.stats.average_block_time = block_time;
    }
}

/// Mining coordinator
pub struct MiningCoordinator {
    /// Mining engine
    mining_engine: MiningEngine,
    /// Transaction selector
    transaction_selector: TransactionSelector,
    /// Mempool manager (real implementation)
    mempool: std::sync::Arc<crate::node::mempool::MempoolManager>,
    /// Storage for UTXO set access
    storage: Option<std::sync::Arc<crate::storage::Storage>>,
    /// Protocol engine for connecting mined blocks
    protocol: Option<std::sync::Arc<blvm_protocol::BitcoinProtocolEngine>>,
}

impl MiningCoordinator {
    /// Create a new mining coordinator with real mempool and storage
    pub fn new(
        mempool: std::sync::Arc<crate::node::mempool::MempoolManager>,
        storage: Option<std::sync::Arc<crate::storage::Storage>>,
    ) -> Self {
        Self {
            mining_engine: MiningEngine::new(),
            transaction_selector: TransactionSelector::new(),
            mempool,
            storage,
            protocol: None,
        }
    }

    /// Create with custom parameters
    pub fn with_params(
        mempool: std::sync::Arc<crate::node::mempool::MempoolManager>,
        storage: Option<std::sync::Arc<crate::storage::Storage>>,
        threads: u32,
        max_block_size: usize,
        max_block_weight: u64,
        min_fee_rate: u64,
    ) -> Self {
        Self {
            mining_engine: MiningEngine::with_threads(threads),
            transaction_selector: TransactionSelector::with_params(
                max_block_size,
                max_block_weight,
                min_fee_rate,
            ),
            mempool,
            storage,
            protocol: None,
        }
    }

    /// Wire protocol engine so mined blocks can be connected to the chain.
    pub fn set_protocol_engine(
        &mut self,
        protocol: std::sync::Arc<blvm_protocol::BitcoinProtocolEngine>,
    ) {
        self.protocol = Some(protocol);
    }

    /// Start the mining coordinator
    pub async fn start(&mut self) -> Result<()> {
        info!(
            "Starting mining coordinator (enabled={})",
            self.mining_engine.is_mining_enabled()
        );
        self.mining_loop().await?;
        Ok(())
    }

    /// Main mining loop
    async fn mining_loop(&mut self) -> Result<()> {
        loop {
            if self.mining_engine.is_mining_enabled() {
                self.mine_block().await?;
            } else {
                // Wait for mining to be enabled
                tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
            }
        }
    }

    /// Mine a block
    async fn mine_block(&mut self) -> Result<()> {
        debug!("Mining block");

        // Generate block template
        let template = self.generate_block_template().await?;

        // Mine the block
        let mined_block = self.mining_engine.mine_template(template).await?;

        // Submit the block
        self.submit_block(mined_block).await?;

        Ok(())
    }

    /// Generate block template
    pub async fn generate_block_template(&mut self) -> Result<Block> {
        debug!("Generating block template");

        // Get chain tip from storage for prev_block_hash and difficulty
        let (prev_block_hash, bits, height) = if let Some(ref storage) = self.storage {
            if let Some(tip_header) = storage
                .chain()
                .get_tip_header()
                .map_err(|e| anyhow::anyhow!("Failed to get tip header: {}", e))?
            {
                let tip_hash = storage
                    .chain()
                    .get_tip_hash()
                    .map_err(|e| anyhow::anyhow!("Failed to get tip hash: {}", e))?
                    .unwrap_or([0u8; 32]);
                let chain_height = storage
                    .chain()
                    .get_height()
                    .map_err(|e| anyhow::anyhow!("Failed to get chain height: {}", e))?
                    .unwrap_or(0);
                (tip_hash, tip_header.bits, chain_height)
            } else {
                // No chain tip - use genesis defaults
                ([0u8; 32], 0x1d00ffff, 0)
            }
        } else {
            // No storage - use defaults
            ([0u8; 32], 0x1d00ffff, 0)
        };

        // Get UTXO set from storage for fee calculation
        let utxo_set = if let Some(ref storage) = self.storage {
            storage
                .utxos()
                .get_all_utxos()
                .map_err(|e| anyhow::anyhow!("Failed to get UTXO set: {}", e))?
        } else {
            // No storage - use empty UTXO set (will result in 0 fees)
            blvm_protocol::UtxoSet::default()
        };

        // Select transactions from mempool (with UTXO set for accurate fee calculation)
        let transactions = self
            .transaction_selector
            .select_transactions(&*self.mempool as &dyn MempoolProvider, &utxo_set);

        // Create coinbase transaction with subsidy + fees
        let coinbase_tx = self
            .create_coinbase_transaction(height + 1, &transactions, &utxo_set)
            .await?;

        // Build transaction list (coinbase first)
        let mut all_transactions = vec![coinbase_tx];
        all_transactions.extend(transactions);

        // Calculate merkle root from transactions (we own all_transactions, so we can mutate it)
        use blvm_protocol::mining::calculate_merkle_root;
        let merkle_root = calculate_merkle_root(&all_transactions)
            .map_err(|e| anyhow::anyhow!("Failed to calculate merkle root: {}", e))?;

        // Get current timestamp
        let timestamp = current_timestamp();

        // Build block template
        let template = Block {
            header: BlockHeader {
                version: 1,
                prev_block_hash,
                merkle_root,
                timestamp,
                bits,
                nonce: 0,
            },
            transactions: all_transactions.into_boxed_slice(),
        };

        debug!(
            "Generated block template: height={}, prev_hash={:?}, {} transactions, merkle_root={:?}",
            height + 1,
            prev_block_hash,
            template.transactions.len(),
            merkle_root
        );

        Ok(template)
    }

    /// Create coinbase transaction with subsidy + fees
    async fn create_coinbase_transaction(
        &self,
        height: u64,
        selected_transactions: &[Transaction],
        utxo_set: &blvm_protocol::UtxoSet,
    ) -> Result<Transaction> {
        use blvm_protocol::ConsensusProof;

        // 1. Get block subsidy from consensus layer
        let consensus = ConsensusProof::new();
        let subsidy = consensus.get_block_subsidy(height) as u64;

        // 2. Calculate total fees from selected transactions
        let total_fees: u64 = selected_transactions
            .iter()
            .map(|tx| self.mempool.calculate_transaction_fee(tx, utxo_set))
            .sum();

        // 3. Coinbase value = subsidy + fees
        let coinbase_value = subsidy.checked_add(total_fees).ok_or_else(|| {
            anyhow::anyhow!(
                "Coinbase value overflow: subsidy {} + fees {}",
                subsidy,
                total_fees
            )
        })?;

        debug!(
            "Creating coinbase: height={}, subsidy={}, fees={}, total={}",
            height, subsidy, total_fees, coinbase_value
        );

        // 4. Create coinbase transaction (BIP34 height in scriptSig; BIP54: lock_time = height - 13, sequence != 0xffffffff)
        let lock_time = height.saturating_sub(13);
        let h = height.min(u64::from(u32::MAX));
        let mut height_bytes = Vec::new();
        let mut x = h;
        while x > 0 {
            height_bytes.push((x & 0xff) as u8);
            x >>= 8;
        }
        if height_bytes.is_empty() {
            height_bytes.push(0);
        }
        let mut script_sig = vec![height_bytes.len() as u8];
        script_sig.extend(height_bytes);
        if script_sig.len() < 2 {
            script_sig = vec![0x01, 0x00];
        }
        Ok(Transaction {
            version: 1,
            inputs: vec![blvm_protocol::TransactionInput {
                prevout: blvm_protocol::OutPoint {
                    hash: [0u8; 32],
                    index: 0xffffffff,
                },
                script_sig,
                sequence: 0xfffffffe,
            }]
            .into(),
            outputs: crate::tx_outputs![blvm_protocol::TransactionOutput {
                value: coinbase_value as i64,
                script_pubkey: vec![
                    blvm_protocol::opcodes::OP_DUP,
                    blvm_protocol::opcodes::OP_HASH160,
                    blvm_protocol::opcodes::PUSH_20_BYTES,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    blvm_protocol::opcodes::OP_EQUALVERIFY,
                    blvm_protocol::opcodes::OP_CHECKSIG,
                ],
            }],
            lock_time,
        })
    }

    /// Submit mined block to the chain via [`SyncCoordinator::connect_mined_block`].
    async fn submit_block(&self, block: Block) -> Result<()> {
        debug!("Submitting mined block");

        let storage = self
            .storage
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Cannot submit mined block: storage not configured"))?;
        let protocol = self.protocol.as_ref().ok_or_else(|| {
            anyhow::anyhow!("Cannot submit mined block: protocol engine not configured")
        })?;

        let (_, tip_height) = storage
            .chain()
            .get_tip_hash_and_height()
            .map_err(|e| anyhow::anyhow!("Failed to get chain tip: {e}"))?;
        let connect_height = tip_height + 1;

        let mut utxo = storage
            .utxos()
            .get_all_utxos()
            .map_err(|e| anyhow::anyhow!("Failed to load UTXO set: {e}"))?;

        let witnesses = self.build_witnesses_for_block(&block, &utxo)?;

        let mut coord = crate::node::sync::SyncCoordinator::new();
        let accepted = coord.connect_mined_block(
            storage.blocks().as_ref(),
            protocol.as_ref(),
            storage,
            &block,
            &witnesses,
            connect_height,
            &mut utxo,
        )?;

        if !accepted {
            anyhow::bail!("Mined block rejected at height {connect_height}");
        }

        info!("Mined block connected at height {connect_height}");
        Ok(())
    }

    /// Build per-transaction witness stacks for block connect (coinbase uses empty stacks).
    fn build_witnesses_for_block(
        &self,
        block: &Block,
        utxo_set: &blvm_protocol::UtxoSet,
    ) -> Result<Vec<Vec<Witness>>> {
        use blvm_consensus::transaction::is_coinbase;
        use blvm_consensus::witness::{
            extract_witness_program, extract_witness_version, validate_witness_program_length,
        };
        use blvm_protocol::block::calculate_tx_id;

        block
            .transactions
            .iter()
            .map(|tx| {
                if is_coinbase(tx) {
                    return Ok(tx.inputs.iter().map(|_| Witness::default()).collect());
                }
                let txid = calculate_tx_id(tx);
                if let Some(wits) = self.mempool.get_transaction_witnesses(&txid) {
                    if wits.len() != tx.inputs.len() {
                        anyhow::bail!(
                            "witness count {} != input count {} for tx {}",
                            wits.len(),
                            tx.inputs.len(),
                            hex::encode(txid)
                        );
                    }
                    return Ok(wits);
                }

                let spends_witness_utxo = tx.inputs.iter().any(|input| {
                    utxo_set.get(&input.prevout).is_some_and(|utxo| {
                        let script = utxo.script_pubkey.as_ref().to_vec();
                        extract_witness_version(&script)
                            .and_then(|version| {
                                extract_witness_program(&script, version)
                                    .map(|program| (version, program))
                            })
                            .is_some_and(|(version, program)| {
                                validate_witness_program_length(&program, version)
                            })
                    })
                });
                if self.mempool.get_transaction(&txid).is_some() && spends_witness_utxo {
                    anyhow::bail!(
                        "missing mempool witnesses for witness spend tx {}",
                        hex::encode(txid)
                    );
                }

                Ok(tx.inputs.iter().map(|_| Witness::default()).collect())
            })
            .collect()
    }

    /// Enable mining
    pub fn enable_mining(&mut self) {
        self.mining_engine.enable_mining();
    }

    /// Disable mining
    pub fn disable_mining(&mut self) {
        self.mining_engine.disable_mining();
    }

    /// Check if mining is enabled
    pub fn is_mining_enabled(&self) -> bool {
        self.mining_engine.is_mining_enabled()
    }

    /// Get mining info
    pub fn get_mining_info(&self) -> MiningInfo {
        MiningInfo {
            enabled: self.mining_engine.is_mining_enabled(),
            threads: self.mining_engine.get_threads(),
            has_template: self.mining_engine.get_block_template().is_some(),
        }
    }

    /// Get mining statistics
    pub fn get_mining_stats(&self) -> &MiningStats {
        self.mining_engine.get_stats()
    }

    /// Get access to the mining engine
    pub fn mining_engine(&self) -> &MiningEngine {
        &self.mining_engine
    }

    /// Get mutable access to the mining engine
    pub fn mining_engine_mut(&mut self) -> &mut MiningEngine {
        &mut self.mining_engine
    }

    /// Get access to the transaction selector
    pub fn transaction_selector(&self) -> &TransactionSelector {
        &self.transaction_selector
    }

    /// Get mutable access to the transaction selector
    pub fn transaction_selector_mut(&mut self) -> &mut TransactionSelector {
        &mut self.transaction_selector
    }

    /// Get mempool size
    pub fn get_mempool_size(&self) -> usize {
        self.mempool.size()
    }
}

/// Mining information
#[derive(Debug, Clone)]
pub struct MiningInfo {
    pub enabled: bool,
    pub threads: u32,
    pub has_template: bool,
}

/// Mock mempool provider for testing
pub struct MockMempoolProvider {
    transactions: HashMap<[u8; 32], Transaction>,
    prioritized_transactions: Vec<(Transaction, u64)>,
}

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

impl MockMempoolProvider {
    pub fn new() -> Self {
        Self {
            transactions: HashMap::new(),
            prioritized_transactions: Vec::new(),
        }
    }

    pub fn add_transaction(&mut self, tx: Transaction) {
        let hash = self.calculate_tx_hash(&tx);
        let fee_rate = self.calculate_fee_rate(&tx);
        self.transactions.insert(hash, tx.clone());
        self.prioritized_transactions.push((tx, fee_rate));
        // Sort by fee rate descending.
        self.prioritized_transactions.sort_by(|a, b| b.1.cmp(&a.1));
    }

    pub fn clear(&mut self) {
        self.transactions.clear();
        self.prioritized_transactions.clear();
    }

    fn calculate_tx_hash(&self, tx: &Transaction) -> [u8; 32] {
        // Simplified hash calculation
        let mut hash = [0u8; 32];
        hash[0] = tx.version as u8;
        hash[1] = tx.inputs.len() as u8;
        hash[2] = tx.outputs.len() as u8;
        hash
    }

    fn calculate_fee_rate(&self, tx: &Transaction) -> u64 {
        // Simplified fee rate calculation - make it vary by version
        let total_output_value: u64 = tx.outputs.iter().map(|out| out.value as u64).sum();
        let total_input_value = total_output_value + (tx.version * 1000); // Mock input value varies by version
        let fee = total_input_value - total_output_value;
        let size = tx.inputs.len() * 148 + tx.outputs.len() * 34 + 10;
        if size == 0 {
            return 0;
        }
        fee / size as u64
    }
}

impl MempoolProvider for MockMempoolProvider {
    fn get_transactions(&self) -> Vec<Transaction> {
        self.transactions.values().cloned().collect()
    }

    fn get_transaction(&self, hash: &[u8; 32]) -> Option<Transaction> {
        self.transactions.get(hash).cloned()
    }

    fn get_mempool_size(&self) -> usize {
        self.transactions.len()
    }

    fn get_prioritized_transactions(
        &self,
        limit: usize,
        _utxo_set: &blvm_protocol::UtxoSet,
    ) -> Vec<Transaction> {
        // Mock implementation ignores UTXO set and uses pre-calculated priorities
        self.prioritized_transactions
            .iter()
            .take(limit)
            .map(|(tx, _)| tx.clone())
            .collect()
    }

    fn remove_transaction(&mut self, hash: &[u8; 32]) -> bool {
        if let Some(tx) = self.transactions.remove(hash) {
            self.prioritized_transactions.retain(|(t, _)| t != &tx);
            true
        } else {
            false
        }
    }

    fn get_transaction_witnesses(&self, _hash: &[u8; 32]) -> Option<Vec<Witness>> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use blvm_protocol::TransactionOutput;

    #[test]
    fn test_transaction_selector_creation() {
        let selector = TransactionSelector::new();
        assert_eq!(selector.max_block_size(), 1_000_000);
        assert_eq!(selector.max_block_weight(), 4_000_000);
        assert_eq!(selector.min_fee_rate(), 1);
    }

    #[test]
    fn test_transaction_selector_with_params() {
        let selector = TransactionSelector::with_params(2_000_000, 8_000_000, 5);
        assert_eq!(selector.max_block_size(), 2_000_000);
        assert_eq!(selector.max_block_weight(), 8_000_000);
        assert_eq!(selector.min_fee_rate(), 5);
    }

    #[test]
    fn test_transaction_selector_transaction_selection() {
        let selector = TransactionSelector::new();
        let mut mempool = MockMempoolProvider::new();

        // Add some test transactions
        let tx1 = create_test_transaction(1, 1000);
        let tx2 = create_test_transaction(2, 2000);
        let tx3 = create_test_transaction(3, 500);

        mempool.add_transaction(tx1);
        mempool.add_transaction(tx2);
        mempool.add_transaction(tx3);

        // UTXO set must contain inputs for fee calculation (create_test_transaction uses [0;32], index 0)
        let mut utxo_set = blvm_protocol::UtxoSet::default();
        let outpoint = blvm_protocol::OutPoint {
            hash: [0u8; 32],
            index: 0,
        };
        utxo_set.insert(
            outpoint,
            std::sync::Arc::new(blvm_protocol::UTXO {
                value: 100_000_000, // 1 BTC - enough for all test tx outputs
                script_pubkey: vec![blvm_protocol::opcodes::OP_1].into(),
                height: 0,
                is_coinbase: false,
            }),
        );

        let selected = selector.select_transactions(&mempool, &utxo_set);
        assert!(!selected.is_empty());
        assert!(selected.len() <= 3);
    }

    #[test]
    fn test_transaction_selector_size_calculation() {
        let selector = TransactionSelector::new();
        let tx = create_test_transaction(1, 1000);

        let vsize = transaction_vsize(&tx, None);
        assert!(vsize > 0);

        let weight = bip141_weight(&tx, None);
        assert!(weight > 0);

        let mut utxo_set = blvm_protocol::UtxoSet::default();
        let outpoint = blvm_protocol::OutPoint {
            hash: [0u8; 32],
            index: 0,
        };
        utxo_set.insert(
            outpoint,
            std::sync::Arc::new(blvm_protocol::UTXO {
                value: 10000,
                script_pubkey: vec![blvm_protocol::opcodes::OP_1].into(),
                height: 0,
                is_coinbase: false,
            }),
        );
        let fee_rate = selector.calculate_fee_rate_with_utxo(&tx, &utxo_set, vsize);
        assert!(fee_rate > 0);
    }

    #[test]
    fn test_mining_engine_creation() {
        let engine = MiningEngine::new();
        assert!(!engine.is_mining_enabled());
        assert_eq!(engine.get_threads(), 1);
        assert!(engine.get_block_template().is_none());
        assert_eq!(engine.get_stats().blocks_mined, 0);
    }

    #[test]
    fn test_mining_engine_with_threads() {
        let engine = MiningEngine::with_threads(4);
        assert!(!engine.is_mining_enabled());
        assert_eq!(engine.get_threads(), 4);
    }

    #[test]
    fn test_mining_engine_enable_disable() {
        let mut engine = MiningEngine::new();

        assert!(!engine.is_mining_enabled());
        engine.enable_mining();
        assert!(engine.is_mining_enabled());

        engine.disable_mining();
        assert!(!engine.is_mining_enabled());
    }

    #[test]
    fn test_mining_engine_thread_management() {
        let mut engine = MiningEngine::new();

        assert_eq!(engine.get_threads(), 1);
        engine.set_threads(8);
        assert_eq!(engine.get_threads(), 8);
    }

    #[tokio::test]
    async fn test_mining_engine_mine_template() {
        let mut engine = MiningEngine::new();
        let template = create_test_block();

        let result = engine.mine_template(template.clone()).await;

        // Mining may succeed (if low difficulty) or fail (if high difficulty)
        // Both are valid outcomes for real PoW mining
        if let Ok(mined_block) = result {
            // Successfully mined - verify the block
            assert_eq!(mined_block.header.version, template.header.version);
            assert_ne!(mined_block.header.nonce, template.header.nonce); // Nonce should change

            // Verify proof of work
            use blvm_protocol::pow::check_proof_of_work;
            let pow_valid = check_proof_of_work(&mined_block.header).unwrap();
            assert!(pow_valid, "Mined block should have valid proof of work");

            // Check that template was stored
            assert!(engine.get_block_template().is_some());
            assert_eq!(engine.get_stats().blocks_mined, 1);
        } else {
            // Mining failed (high difficulty) - this is expected for mainnet difficulty
            // Just verify the template was stored
            assert!(engine.get_block_template().is_some());
        }
    }

    #[tokio::test]
    async fn test_mining_engine_mine_template_multithreaded() {
        let mut engine = MiningEngine::with_threads(4);
        let template = create_test_block();

        let result = engine.mine_template(template.clone()).await;

        // Mining may succeed (if low difficulty) or fail (if high difficulty)
        if let Ok(mined_block) = result {
            // Successfully mined - verify the block
            assert_eq!(mined_block.header.version, template.header.version);

            // Verify proof of work
            use blvm_protocol::pow::check_proof_of_work;
            let pow_valid = check_proof_of_work(&mined_block.header).unwrap();
            assert!(pow_valid, "Mined block should have valid proof of work");

            // Check that template was stored
            assert!(engine.get_block_template().is_some());
            assert_eq!(engine.get_stats().blocks_mined, 1);
        } else {
            // Mining failed (high difficulty) - this is expected
            assert!(engine.get_block_template().is_some());
        }
    }

    #[tokio::test]
    async fn test_mining_engine_mine_template_regtest_difficulty() {
        // Test with mainnet difficulty - mining may succeed or fail depending on luck
        // This tests that the mining infrastructure works correctly
        let mut engine = MiningEngine::new();
        let template = create_test_block();
        // template already has bits: 0x1d00ffff (mainnet difficulty)

        let result = engine.mine_template(template.clone()).await;

        // Mining may succeed (if we find a nonce) or fail (if we don't within max_attempts)
        // Both are valid outcomes for real PoW mining
        if let Ok(mined_block) = result {
            // Successfully mined - verify the block
            assert_eq!(mined_block.header.version, template.header.version);
            assert_ne!(mined_block.header.nonce, template.header.nonce);

            // Verify proof of work
            use blvm_protocol::pow::check_proof_of_work;
            let pow_valid = check_proof_of_work(&mined_block.header).unwrap();
            assert!(pow_valid, "Mined block should have valid proof of work");

            // Check statistics
            assert_eq!(engine.get_stats().blocks_mined, 1);
        } else {
            // Mining failed (didn't find nonce within max_attempts) - this is expected
            // The important thing is that the mining infrastructure worked correctly
            assert!(engine.get_block_template().is_some());
        }
    }

    #[test]
    fn test_mining_engine_template_management() {
        let mut engine = MiningEngine::new();

        assert!(engine.get_block_template().is_none());

        let template = create_test_block();
        engine.block_template = Some(template.clone());

        assert!(engine.get_block_template().is_some());
        assert_eq!(
            engine.get_block_template().unwrap().header.version,
            template.header.version
        );

        engine.clear_template();
        assert!(engine.get_block_template().is_none());
    }

    #[test]
    fn test_mining_engine_statistics() {
        let mut engine = MiningEngine::new();
        let stats = engine.get_stats();

        assert_eq!(stats.blocks_mined, 0);
        assert_eq!(stats.total_hashrate, 0.0);
        assert_eq!(stats.average_block_time, 0.0);
        assert!(stats.last_block_time.is_none());

        engine.update_hashrate(1000.0);
        assert_eq!(engine.get_stats().total_hashrate, 1000.0);

        engine.update_average_block_time(600.0);
        assert_eq!(engine.get_stats().average_block_time, 600.0);
    }

    #[test]
    fn test_mock_mempool_provider_creation() {
        let mempool = MockMempoolProvider::new();
        assert_eq!(mempool.get_mempool_size(), 0);
        assert!(mempool.get_transactions().is_empty());
        let empty_utxo_set = blvm_protocol::UtxoSet::default();
        assert!(
            mempool
                .get_prioritized_transactions(10, &empty_utxo_set)
                .is_empty()
        );
    }

    #[test]
    fn test_mock_mempool_provider_transaction_management() {
        let mut mempool = MockMempoolProvider::new();

        let tx1 = create_test_transaction(1, 1000);
        let tx2 = create_test_transaction(2, 2000);

        mempool.add_transaction(tx1.clone());
        mempool.add_transaction(tx2.clone());

        assert_eq!(mempool.get_mempool_size(), 2);
        assert_eq!(mempool.get_transactions().len(), 2);

        let empty_utxo_set = blvm_protocol::UtxoSet::default();
        let prioritized = mempool.get_prioritized_transactions(10, &empty_utxo_set);
        assert_eq!(prioritized.len(), 2);

        // Test transaction removal
        let hash = mempool.calculate_tx_hash(&tx1);
        assert!(mempool.remove_transaction(&hash));
        assert_eq!(mempool.get_mempool_size(), 1);

        // Test removal of non-existent transaction
        let fake_hash = [0u8; 32];
        assert!(!mempool.remove_transaction(&fake_hash));
    }

    #[test]
    fn test_mock_mempool_provider_prioritization() {
        let mut mempool = MockMempoolProvider::new();

        // Add transactions with different fee rates
        let tx_low_fee = create_test_transaction(1, 100); // Low fee
        let tx_high_fee = create_test_transaction(2, 5000); // High fee
        let tx_medium_fee = create_test_transaction(3, 1000); // Medium fee

        mempool.add_transaction(tx_low_fee);
        mempool.add_transaction(tx_high_fee);
        mempool.add_transaction(tx_medium_fee);

        let empty_utxo_set = blvm_protocol::UtxoSet::default();
        let prioritized = mempool.get_prioritized_transactions(10, &empty_utxo_set);
        assert_eq!(prioritized.len(), 3);

        // Transactions should be sorted by fee rate (descending)
        // Version 3 (medium fee) should be first, then version 2 (high fee), then version 1 (low fee)
        assert_eq!(prioritized[0].version, 3);
        assert_eq!(prioritized[1].version, 2);
        assert_eq!(prioritized[2].version, 1);
    }

    #[test]
    fn test_mock_mempool_provider_clear() {
        let mut mempool = MockMempoolProvider::new();

        let tx = create_test_transaction(1, 1000);
        mempool.add_transaction(tx);

        assert_eq!(mempool.get_mempool_size(), 1);

        mempool.clear();
        assert_eq!(mempool.get_mempool_size(), 0);
        assert!(mempool.get_transactions().is_empty());
    }

    #[test]
    fn test_mining_coordinator_creation() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::new(mempool, None);

        assert!(!coordinator.is_mining_enabled());
        assert_eq!(coordinator.get_mempool_size(), 0);
        assert_eq!(coordinator.mining_engine().get_threads(), 1);
        assert_eq!(
            coordinator.transaction_selector().max_block_size(),
            1_000_000
        );
    }

    #[test]
    fn test_mining_coordinator_with_params() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::with_params(mempool, None, 4, 2_000_000, 8_000_000, 5);

        assert_eq!(coordinator.mining_engine().get_threads(), 4);
        assert_eq!(
            coordinator.transaction_selector().max_block_size(),
            2_000_000
        );
        assert_eq!(
            coordinator.transaction_selector().max_block_weight(),
            8_000_000
        );
        assert_eq!(coordinator.transaction_selector().min_fee_rate(), 5);
    }

    #[test]
    fn test_mining_coordinator_enable_disable() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let mut coordinator = MiningCoordinator::new(mempool, None);

        assert!(!coordinator.is_mining_enabled());
        coordinator.enable_mining();
        assert!(coordinator.is_mining_enabled());

        coordinator.disable_mining();
        assert!(!coordinator.is_mining_enabled());
    }

    #[test]
    fn test_mining_coordinator_info() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::new(mempool, None);

        let info = coordinator.get_mining_info();
        assert!(!info.enabled);
        assert_eq!(info.threads, 1);
        assert!(!info.has_template);
    }

    #[test]
    fn test_mining_coordinator_statistics() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::new(mempool, None);

        let stats = coordinator.get_mining_stats();
        assert_eq!(stats.blocks_mined, 0);
        assert_eq!(stats.total_hashrate, 0.0);
        assert_eq!(stats.average_block_time, 0.0);
        assert!(stats.last_block_time.is_none());
    }

    #[test]
    fn test_mining_coordinator_accessors() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::new(mempool, None);

        // Test immutable access
        let engine = coordinator.mining_engine();
        assert_eq!(engine.get_threads(), 1);

        let selector = coordinator.transaction_selector();
        assert_eq!(selector.max_block_size(), 1_000_000);

        // Test mutable access
        let mut coordinator = coordinator;
        let engine_mut = coordinator.mining_engine_mut();
        engine_mut.set_threads(4);
        assert_eq!(coordinator.mining_engine().get_threads(), 4);

        let selector_mut = coordinator.transaction_selector_mut();
        // Test that we can access the selector
        assert_eq!(selector_mut.max_block_size(), 1_000_000);
    }

    #[tokio::test]
    async fn test_mining_coordinator_mempool_operations() {
        use std::sync::Arc;
        // Create mempool and add transaction before wrapping in Arc
        let mut mempool_manager = crate::node::mempool::MempoolManager::new();
        let tx = create_test_transaction(1, 1000);
        let _ = mempool_manager.add_transaction(tx);
        let mempool = Arc::new(mempool_manager);
        let coordinator = MiningCoordinator::new(mempool, None);

        assert_eq!(coordinator.get_mempool_size(), 1);
    }

    #[tokio::test]
    async fn test_mining_coordinator_block_template_generation() {
        use std::sync::Arc;
        // Create mempool and add transaction before wrapping in Arc
        let mut mempool_manager = crate::node::mempool::MempoolManager::new();
        let tx = create_test_transaction(1, 1000);
        let _ = mempool_manager.add_transaction(tx);
        let mempool = Arc::new(mempool_manager);

        let mut coordinator = MiningCoordinator::new(mempool, None);

        let template = coordinator.generate_block_template().await;
        assert!(template.is_ok());

        let block = template.unwrap();
        assert_eq!(block.header.version, 1);
        assert!(!block.transactions.is_empty()); // Should have coinbase + mempool tx
    }

    #[tokio::test]
    async fn test_mining_coordinator_coinbase_creation() {
        use std::sync::Arc;
        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let coordinator = MiningCoordinator::new(mempool, None);

        // Test coinbase creation with no transactions (subsidy only)
        let empty_utxo_set = blvm_protocol::UtxoSet::default();
        let coinbase = coordinator
            .create_coinbase_transaction(0, &[], &empty_utxo_set)
            .await;
        assert!(coinbase.is_ok());

        let tx = coinbase.unwrap();
        assert_eq!(tx.version, 1);
        // Bitcoin coinbase: exactly one input, null prevout + 0xffffffff index (BIP30/BIP34).
        assert_eq!(tx.inputs.len(), 1);
        assert_eq!(tx.inputs[0].prevout.hash, [0u8; 32]);
        assert_eq!(tx.inputs[0].prevout.index, 0xffff_ffff);
        assert_eq!(tx.outputs.len(), 1);
        // Should be 50 BTC (subsidy) at height 0, with no fees
        assert_eq!(tx.outputs[0].value, 5000000000); // 50 BTC
        assert_eq!(tx.lock_time, 0);
    }

    // Helper functions for tests
    fn create_test_transaction(version: i32, output_value: u64) -> Transaction {
        use blvm_protocol::{OutPoint, TransactionInput};
        Transaction {
            version: version as u64,
            inputs: blvm_protocol::tx_inputs![TransactionInput {
                prevout: OutPoint {
                    hash: [0u8; 32],
                    index: 0,
                },
                script_sig: vec![
                    blvm_protocol::opcodes::OP_DUP,
                    blvm_protocol::opcodes::OP_HASH160,
                    blvm_protocol::opcodes::PUSH_20_BYTES,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    blvm_protocol::opcodes::OP_EQUALVERIFY,
                    blvm_protocol::opcodes::OP_CHECKSIG,
                ],
                sequence: 0xffffffff,
            }],
            outputs: blvm_protocol::tx_outputs![TransactionOutput {
                value: output_value as i64,
                script_pubkey: vec![
                    blvm_protocol::opcodes::OP_DUP,
                    blvm_protocol::opcodes::OP_HASH160,
                    blvm_protocol::opcodes::PUSH_20_BYTES,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    0x00,
                    blvm_protocol::opcodes::OP_EQUALVERIFY,
                    blvm_protocol::opcodes::OP_CHECKSIG,
                ],
            }],
            lock_time: 0,
        }
    }

    fn create_test_block() -> Block {
        Block {
            header: BlockHeader {
                version: 1,
                prev_block_hash: [0u8; 32],
                merkle_root: [0u8; 32],
                timestamp: 1231006505,
                bits: 0x1d00ffff,
                nonce: 0,
            },
            transactions: vec![create_test_transaction(1, 1000)].into_boxed_slice(),
        }
    }

    #[tokio::test]
    async fn test_build_witnesses_uses_mempool_stored_witnesses() {
        use blvm_protocol::{OutPoint, TransactionInput, TransactionOutput};
        use sha2::{Digest, Sha256};
        use std::sync::Arc;

        fn p2wsh_scriptpubkey(witness_script: &[u8]) -> Vec<u8> {
            let hash = Sha256::digest(witness_script);
            let mut spk = vec![blvm_protocol::opcodes::OP_0, 0x20];
            spk.extend_from_slice(&hash);
            spk
        }

        let witness_script = vec![0x51]; // OP_1
        let funding_hash = [0xab; 32];
        let mut utxo_set = blvm_protocol::UtxoSet::default();
        utxo_set.insert(
            OutPoint {
                hash: funding_hash,
                index: 0,
            },
            Arc::new(blvm_protocol::UTXO {
                value: 100_000,
                script_pubkey: p2wsh_scriptpubkey(&witness_script).into(),
                height: 0,
                is_coinbase: false,
            }),
        );

        let spend = Transaction {
            version: 2,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: funding_hash,
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xfffffffe,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 90_000,
                script_pubkey: vec![0x51],
            }]
            .into(),
            lock_time: 0,
        };
        let txid = blvm_protocol::block::calculate_tx_id(&spend);
        let witness_stack: Witness = vec![witness_script.clone()];

        let mut mempool_manager = crate::node::mempool::MempoolManager::new();
        assert!(
            mempool_manager
                .add_transaction_with_witness(spend.clone(), Some(vec![witness_stack.clone()]))
                .unwrap(),
            "witness tx must enter mempool"
        );
        let mempool = Arc::new(mempool_manager);
        let coordinator = MiningCoordinator::new(mempool, None);

        let coinbase = coordinator
            .create_coinbase_transaction(1, &[spend.clone()], &utxo_set)
            .await
            .unwrap();
        let block = Block {
            header: BlockHeader {
                version: 1,
                prev_block_hash: [0u8; 32],
                merkle_root: [0u8; 32],
                timestamp: 1,
                bits: 0x1d00ffff,
                nonce: 0,
            },
            transactions: vec![coinbase, spend].into_boxed_slice(),
        };

        let witnesses = coordinator
            .build_witnesses_for_block(&block, &utxo_set)
            .expect("witness spend with stored mempool witnesses");
        assert_eq!(witnesses.len(), 2);
        assert!(witnesses[0].iter().all(|w| w.is_empty()));
        assert_eq!(witnesses[1], vec![witness_stack.clone()]);
        assert_eq!(
            coordinator.mempool.get_transaction_witnesses(&txid),
            Some(vec![witness_stack])
        );
    }

    #[tokio::test]
    async fn test_build_witnesses_fails_when_mempool_missing_witness_spend() {
        use blvm_protocol::{OutPoint, TransactionInput, TransactionOutput};
        use sha2::{Digest, Sha256};
        use std::sync::Arc;

        fn p2wsh_scriptpubkey(witness_script: &[u8]) -> Vec<u8> {
            let hash = Sha256::digest(witness_script);
            let mut spk = vec![blvm_protocol::opcodes::OP_0, 0x20];
            spk.extend_from_slice(&hash);
            spk
        }

        let witness_script = vec![0x51];
        let funding_hash = [0xcd; 32];
        let mut utxo_set = blvm_protocol::UtxoSet::default();
        utxo_set.insert(
            OutPoint {
                hash: funding_hash,
                index: 0,
            },
            Arc::new(blvm_protocol::UTXO {
                value: 100_000,
                script_pubkey: p2wsh_scriptpubkey(&witness_script).into(),
                height: 0,
                is_coinbase: false,
            }),
        );

        let spend = Transaction {
            version: 2,
            inputs: vec![TransactionInput {
                prevout: OutPoint {
                    hash: funding_hash,
                    index: 0,
                },
                script_sig: vec![],
                sequence: 0xfffffffe,
            }]
            .into(),
            outputs: vec![TransactionOutput {
                value: 90_000,
                script_pubkey: vec![0x51],
            }]
            .into(),
            lock_time: 0,
        };

        let mut mempool_manager = crate::node::mempool::MempoolManager::new();
        assert!(
            mempool_manager.add_transaction(spend.clone()).unwrap(),
            "tx must enter mempool"
        );
        let mempool = Arc::new(mempool_manager);
        let coordinator = MiningCoordinator::new(mempool, None);

        let coinbase = coordinator
            .create_coinbase_transaction(1, &[spend.clone()], &utxo_set)
            .await
            .unwrap();
        let block = Block {
            header: BlockHeader {
                version: 1,
                prev_block_hash: [0u8; 32],
                merkle_root: [0u8; 32],
                timestamp: 1,
                bits: 0x1d00ffff,
                nonce: 0,
            },
            transactions: vec![coinbase, spend].into_boxed_slice(),
        };

        let err = coordinator
            .build_witnesses_for_block(&block, &utxo_set)
            .unwrap_err();
        assert!(
            err.to_string().contains("missing mempool witnesses"),
            "unexpected error: {err}"
        );
    }

    /// REV-TN-04: template → mine → `submit_block` → `connect_mined_block` on regtest storage.
    #[tokio::test]
    async fn test_submit_block_connects_regtest() {
        use blvm_protocol::{BitcoinProtocolEngine, ProtocolVersion};
        use std::sync::Arc;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let storage = Arc::new(crate::storage::Storage::new(temp_dir.path()).unwrap());
        let protocol = Arc::new(BitcoinProtocolEngine::new(ProtocolVersion::Regtest).unwrap());
        let genesis = protocol.get_network_params().genesis_block.header.clone();
        storage.chain().initialize(&genesis).unwrap();

        let mempool = Arc::new(crate::node::mempool::MempoolManager::new());
        let mut coordinator = MiningCoordinator::new(mempool, Some(Arc::clone(&storage)));
        coordinator.set_protocol_engine(Arc::clone(&protocol));

        assert_eq!(
            storage.chain().get_height().unwrap().unwrap_or(0),
            0,
            "genesis only"
        );

        let mut template = coordinator
            .generate_block_template()
            .await
            .expect("block template");
        assert_eq!(template.transactions.len(), 1, "coinbase only");
        // BIP90: post-genesis blocks need version ≥ 4 (same as `generatetoaddress` RPC path).
        template.header.version = 4;

        let mined = coordinator
            .mining_engine_mut()
            .mine_template(template)
            .await
            .expect("regtest PoW should succeed");

        coordinator
            .submit_block(mined)
            .await
            .expect("submit connects mined block");

        let height = storage
            .chain()
            .get_height()
            .unwrap()
            .expect("height after connect");
        assert_eq!(height, 1, "mined block extends chain from genesis");
    }
}