blvm-node 0.1.2

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
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
//! Node API implementation for modules
//!
//! Provides a NodeAPI implementation that modules can use to query the node state.

use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::debug;

/// Thread-local storage for current module ID during API calls
thread_local! {
    static CURRENT_MODULE_ID: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

use crate::module::api::events::EventManager;
use crate::module::hooks::HookManager;
use crate::module::ipc::protocol::EventPayload;
use crate::module::ipc::protocol::ModuleMessage;
use crate::module::metrics::manager::{Metric, MetricsManager};
use crate::module::traits::{
    module_error_msg, BlockServeDenylistSnapshot, ChainInfo, EventType, LightningInfo, MempoolSize,
    ModuleError, ModuleInfo, ModuleState, NetworkStats, NodeAPI, PaymentState, PeerInfo,
    SubmitBlockResult, SyncStatus, TxServeDenylistSnapshot,
};
use crate::network::{transport::TransportAddr, NetworkManager};
use crate::node::mempool::MempoolManager;
use crate::storage::Storage;
use crate::{Block, BlockHeader, Hash, OutPoint, Transaction, UTXO};
use hex;

/// Node API implementation for modules
pub struct NodeApiImpl {
    /// Storage reference for querying blockchain data
    storage: Arc<Storage>,
    /// Event manager for event subscriptions
    event_manager: Option<Arc<EventManager>>,
    /// Module ID for this API instance (used for event subscriptions)
    module_id: Option<String>,
    /// Mempool manager (optional, for mempool queries)
    mempool_manager: Option<Arc<MempoolManager>>,
    /// Network manager (optional, for network queries)
    network_manager: Option<Arc<NetworkManager>>,
    /// RPC server (optional, for RPC endpoint registration)
    rpc_server: Option<Arc<crate::rpc::server::RpcServer>>,
    /// Hook manager (optional, for module hooks)
    hook_manager: Option<Arc<tokio::sync::RwLock<HookManager>>>,
    /// Timer manager (optional, for timers and scheduled tasks)
    timer_manager: Option<Arc<crate::module::timers::manager::TimerManager>>,
    /// Module ID (for timer/task registration)
    module_id_for_timers: Option<String>,
    /// Metrics manager (optional, for metrics reporting)
    metrics_manager: Option<Arc<MetricsManager>>,
    /// Module ID (for metrics reporting)
    module_id_for_metrics: Option<String>,
    /// Filesystem sandbox for path validation
    filesystem_sandbox: Option<Arc<crate::module::sandbox::filesystem::FileSystemSandbox>>,
    /// Module data directory path
    module_data_dir: Option<std::path::PathBuf>,
    /// Per-module filesystem sandboxes (module_id -> sandbox)
    module_filesystem_sandboxes: Arc<
        tokio::sync::RwLock<
            std::collections::HashMap<
                String,
                Arc<crate::module::sandbox::filesystem::FileSystemSandbox>,
            >,
        >,
    >,
    /// Per-module data directories (module_id -> path)
    module_data_dirs:
        Arc<tokio::sync::RwLock<std::collections::HashMap<String, std::path::PathBuf>>>,
    /// IPC server reference (for RPC endpoint registration)
    ipc_server: Option<Arc<tokio::sync::Mutex<crate::module::ipc::server::ModuleIpcServer>>>,
    /// Sync coordinator (optional, for sync status checking)
    sync_coordinator: Option<Arc<tokio::sync::Mutex<crate::node::sync::SyncCoordinator>>>,
    /// Payment state machine (optional, for payment state queries)
    payment_state_machine: Option<Arc<crate::payment::state_machine::PaymentStateMachine>>,
    /// Module manager (optional, for module discovery)
    module_manager: Option<Arc<tokio::sync::Mutex<crate::module::manager::ModuleManager>>>,
    /// Module API registry (for module-to-module communication)
    module_api_registry: Option<Arc<crate::module::inter_module::registry::ModuleApiRegistry>>,
    /// Module router (for routing module-to-module calls)
    module_router: Option<Arc<crate::module::inter_module::router::ModuleRouter>>,
    /// Current module ID (for API registration)
    current_module_id_for_api: Option<String>,
}

impl NodeApiImpl {
    /// Create a new Node API implementation
    pub fn new(storage: Arc<Storage>) -> Self {
        let storage_clone = Arc::clone(&storage);
        Self {
            storage,
            event_manager: None,
            module_id: None,
            mempool_manager: None,
            network_manager: None,
            rpc_server: None,
            hook_manager: None,
            timer_manager: None,
            module_id_for_timers: None,
            metrics_manager: None,
            module_id_for_metrics: None,
            filesystem_sandbox: None,
            module_data_dir: None,
            module_filesystem_sandboxes: Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            module_data_dirs: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
            ipc_server: None,
            sync_coordinator: None,
            payment_state_machine: None,
            module_manager: None,
            module_api_registry: None,
            module_router: None,
            current_module_id_for_api: None,
        }
    }

    /// Create a new Node API implementation with event manager
    pub fn with_event_manager(
        storage: Arc<Storage>,
        event_manager: Arc<EventManager>,
        module_id: String,
    ) -> Self {
        Self {
            storage,
            event_manager: Some(event_manager),
            module_id: Some(module_id),
            mempool_manager: None,
            network_manager: None,
            rpc_server: None,
            hook_manager: None,
            timer_manager: None,
            module_id_for_timers: None,
            metrics_manager: None,
            module_id_for_metrics: None,
            filesystem_sandbox: None,
            module_data_dir: None,
            module_filesystem_sandboxes: Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            module_data_dirs: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
            ipc_server: None,
            sync_coordinator: None,
            payment_state_machine: None,
            module_manager: None,
            module_api_registry: None,
            module_router: None,
            current_module_id_for_api: None,
        }
    }

    /// Create a new Node API implementation with all dependencies
    pub fn with_dependencies(
        storage: Arc<Storage>,
        event_manager: Option<Arc<EventManager>>,
        module_id: Option<String>,
        mempool_manager: Option<Arc<MempoolManager>>,
        network_manager: Option<Arc<NetworkManager>>,
    ) -> Self {
        let storage_clone = Arc::clone(&storage);
        Self {
            storage,
            event_manager,
            module_id,
            mempool_manager,
            network_manager,
            rpc_server: None,
            hook_manager: None,
            ipc_server: None,
            timer_manager: None,
            module_id_for_timers: None,
            metrics_manager: None,
            module_id_for_metrics: None,
            filesystem_sandbox: None,
            module_data_dir: None,
            module_filesystem_sandboxes: Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            module_data_dirs: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
            sync_coordinator: None,
            payment_state_machine: None,
            module_manager: None,
            module_api_registry: None,
            module_router: None,
            current_module_id_for_api: None,
        }
    }

    /// Set module manager (for module discovery)
    pub fn set_module_manager(
        &mut self,
        module_manager: Arc<tokio::sync::Mutex<crate::module::manager::ModuleManager>>,
    ) {
        self.module_manager = Some(module_manager);
    }

    /// Set module API registry and router (for module-to-module communication)
    pub fn set_module_api_registry(
        &mut self,
        registry: Arc<crate::module::inter_module::registry::ModuleApiRegistry>,
        router: Arc<crate::module::inter_module::router::ModuleRouter>,
    ) {
        self.module_api_registry = Some(registry);
        self.module_router = Some(router);
    }

    /// Set current module ID (for API registration)
    pub fn set_current_module_id_for_api(&mut self, module_id: String) {
        self.current_module_id_for_api = Some(module_id);
    }

    /// Initialize filesystem and storage access for a module
    pub async fn initialize_module(
        &self,
        module_id: String,
        module_data_dir: std::path::PathBuf,
        base_data_dir: std::path::PathBuf,
    ) -> Result<(), ModuleError> {
        // Create filesystem sandbox for this module
        let sandbox = Arc::new(crate::module::sandbox::filesystem::FileSystemSandbox::new(
            &base_data_dir,
        ));

        // Store per-module state
        {
            let mut sandboxes = self.module_filesystem_sandboxes.write().await;
            sandboxes.insert(module_id.clone(), sandbox);
        }

        {
            let mut dirs = self.module_data_dirs.write().await;
            dirs.insert(module_id.clone(), module_data_dir);
        }

        Ok(())
    }

    /// Get module ID from context (for filesystem/storage operations)
    /// First tries thread-local (set by API hub), then falls back to instance module_id
    fn get_module_id(&self) -> Option<String> {
        CURRENT_MODULE_ID
            .with(|id| id.borrow().clone())
            .or_else(|| self.module_id.clone())
    }

    /// Set current module ID in thread-local (for API hub to use)
    pub fn set_current_module_id(module_id: String) {
        CURRENT_MODULE_ID.with(|id| {
            *id.borrow_mut() = Some(module_id);
        });
    }

    /// Clear current module ID from thread-local
    pub fn clear_current_module_id() {
        CURRENT_MODULE_ID.with(|id| {
            *id.borrow_mut() = None;
        });
    }

    /// Set filesystem sandbox and module data directory (for late initialization - deprecated, use initialize_module)
    pub fn set_filesystem_access(
        &mut self,
        sandbox: Arc<crate::module::sandbox::filesystem::FileSystemSandbox>,
        data_dir: std::path::PathBuf,
    ) {
        self.filesystem_sandbox = Some(sandbox);
        self.module_data_dir = Some(data_dir);
    }

    /// Set hook manager (for late initialization)
    pub fn set_hook_manager(&mut self, hook_manager: Arc<tokio::sync::RwLock<HookManager>>) {
        self.hook_manager = Some(hook_manager);
    }

    /// Set timer manager (for late initialization)
    pub fn set_timer_manager(
        &mut self,
        timer_manager: Arc<crate::module::timers::manager::TimerManager>,
        module_id: String,
    ) {
        self.timer_manager = Some(timer_manager);
        self.module_id_for_timers = Some(module_id);
    }

    /// Set RPC server (for late initialization)
    pub fn set_rpc_server(&mut self, rpc_server: Arc<crate::rpc::server::RpcServer>) {
        self.rpc_server = Some(rpc_server);
    }

    /// Set event manager (for late initialization)
    pub fn set_event_manager(&mut self, event_manager: Arc<EventManager>, module_id: String) {
        self.event_manager = Some(event_manager);
        self.module_id = Some(module_id);
    }

    /// Set mempool manager (for late initialization)
    pub fn set_mempool_manager(&mut self, mempool_manager: Arc<MempoolManager>) {
        self.mempool_manager = Some(mempool_manager);
    }

    /// Set network manager (for late initialization)
    pub fn set_network_manager(&mut self, network_manager: Arc<NetworkManager>) {
        self.network_manager = Some(network_manager);
    }

    /// Set sync coordinator (for late initialization)
    pub fn set_sync_coordinator(
        &mut self,
        sync_coordinator: Arc<tokio::sync::Mutex<crate::node::sync::SyncCoordinator>>,
    ) {
        self.sync_coordinator = Some(sync_coordinator);
    }

    /// Set payment state machine (for late initialization)
    pub fn set_payment_state_machine(
        &mut self,
        payment_state_machine: Arc<crate::payment::state_machine::PaymentStateMachine>,
    ) {
        self.payment_state_machine = Some(payment_state_machine);
    }

    /// Helper to calculate difficulty from bits (private helper, not part of trait).
    /// Uses blvm-consensus difficulty_from_bits (MAX_TARGET / target).
    fn calculate_difficulty_from_bits_helper(&self, bits: u64) -> f64 {
        blvm_protocol::pow::difficulty_from_bits(bits).unwrap_or(1.0)
    }
}

#[async_trait]
impl NodeAPI for NodeApiImpl {
    async fn get_block(&self, hash: &Hash) -> Result<Option<Block>, ModuleError> {
        // Query block store (synchronous operation, but we're in async context)
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let hash = *hash;
            move || {
                storage
                    .blocks()
                    .get_block(&hash)
                    .map_err(|e| ModuleError::op_err("Failed to get block", e))
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn get_block_header(&self, hash: &Hash) -> Result<Option<BlockHeader>, ModuleError> {
        // Query block store for header
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let hash = *hash;
            move || {
                storage
                    .blocks()
                    .get_header(&hash)
                    .map_err(|e| ModuleError::op_err("Failed to get block header", e))
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn get_transaction(&self, hash: &Hash) -> Result<Option<Transaction>, ModuleError> {
        // Query transaction index
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let hash = *hash;
            move || {
                storage
                    .transactions()
                    .get_transaction(&hash)
                    .map_err(|e| ModuleError::op_err("Failed to get transaction", e))
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn has_transaction(&self, hash: &Hash) -> Result<bool, ModuleError> {
        // Check if transaction exists in index
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let hash = *hash;
            move || {
                storage
                    .transactions()
                    .has_transaction(&hash)
                    .map_err(|e| ModuleError::op_err("Failed to check transaction existence", e))
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn get_block_height(&self) -> Result<u64, ModuleError> {
        // Get block height from chain state
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            move || {
                storage
                    .chain()
                    .get_height()
                    .map_err(|e| ModuleError::op_err("Failed to get block height", e))?
                    .ok_or_else(|| {
                        ModuleError::OperationError(
                            module_error_msg::CHAIN_NOT_YET_INITIALIZED.to_string(),
                        )
                    })
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn get_chain_tip(&self) -> Result<Hash, ModuleError> {
        // Get chain tip from chain state
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            move || {
                storage
                    .chain()
                    .get_tip_hash()
                    .map_err(|e| ModuleError::op_err("Failed to get chain tip", e))?
                    .ok_or_else(|| {
                        ModuleError::OperationError(
                            module_error_msg::CHAIN_NOT_YET_INITIALIZED.to_string(),
                        )
                    })
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn get_utxo(&self, outpoint: &OutPoint) -> Result<Option<UTXO>, ModuleError> {
        // Query UTXO store (read-only)
        // Note: This is read-only, modules cannot modify UTXO set
        let outpoint_clone = *outpoint;
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            move || {
                storage
                    .utxos()
                    .get_utxo(&outpoint_clone)
                    .map_err(|e| ModuleError::op_err("Failed to get UTXO", e))
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    async fn subscribe_events(
        &self,
        event_types: Vec<EventType>,
    ) -> Result<mpsc::Receiver<ModuleMessage>, ModuleError> {
        // Create event subscription channel
        let (tx, rx) = mpsc::channel(100);

        // Integrate with event manager if available
        if let (Some(event_manager), Some(module_id)) = (&self.event_manager, &self.module_id) {
            // Register module with event manager
            event_manager
                .subscribe_module(module_id.clone(), event_types, tx)
                .await?;
        } else {
            // Event manager not available - return empty receiver
            // This can happen if NodeAPI is used without event manager setup
            // (e.g., in tests or direct API usage)
            tracing::debug!(
                "Event manager not available for subscribe_events - returning empty receiver"
            );
        }

        Ok(rx)
    }

    // === Mempool API Methods ===
    async fn get_mempool_transactions(&self) -> Result<Vec<Hash>, ModuleError> {
        let mempool = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        // Get all transaction hashes from mempool
        Ok(mempool.transaction_hashes())
    }

    async fn get_mempool_transaction(
        &self,
        tx_hash: &Hash,
    ) -> Result<Option<Transaction>, ModuleError> {
        let mempool = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        Ok(mempool.get_transaction(tx_hash))
    }

    async fn get_mempool_size(&self) -> Result<MempoolSize, ModuleError> {
        // Check hooks for cached value first
        if let Some(hook_mgr) = &self.hook_manager {
            let hooks = hook_mgr.read().await;
            if let Some(cached_stats) = hooks.get_mempool_stats_cached().await {
                return Ok(cached_stats);
            }
        }

        // Fall back to normal calculation
        let mempool = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let transaction_count = mempool.size();
        let transactions = mempool.get_transactions();

        // Calculate total size and fees
        let size_bytes: usize = transactions
            .iter()
            .map(|tx| {
                // Approximate size: serialize to get actual size
                bincode::serialize(tx).map(|bytes| bytes.len()).unwrap_or(0)
            })
            .sum();

        // Calculate total fee from transactions
        let total_fee_sats = tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let transactions_clone = transactions.clone();
            move || {
                let mut total_fee = 0u64;
                for tx in transactions_clone {
                    // Skip coinbase transactions (no fee)
                    if tx.inputs.is_empty() || tx.inputs[0].prevout.hash == [0u8; 32] {
                        continue;
                    }

                    // Calculate fee: sum(inputs) - sum(outputs)
                    let mut input_total = 0u64;
                    for input in &tx.inputs {
                        if let Ok(Some(utxo)) = storage.utxos().get_utxo(&input.prevout) {
                            input_total = input_total.saturating_add(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);
                    total_fee = total_fee.saturating_add(fee);
                }
                total_fee
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?;

        Ok(MempoolSize {
            transaction_count,
            size_bytes,
            total_fee_sats,
        })
    }

    // === Network API Methods ===
    async fn get_network_stats(&self) -> Result<NetworkStats, ModuleError> {
        let network = self.network_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let peer_count = network.peer_count();

        // Get network hash rate from storage (if available)
        let hash_rate = tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            move || {
                // Try to get network hashrate from chain state cache
                if let Ok(Some(chain_info)) = storage.chain().load_chain_info() {
                    // Calculate approximate hash rate from difficulty
                    // Hash rate = difficulty * 2^32 / 600 (seconds per block)
                    let difficulty =
                        blvm_protocol::pow::difficulty_from_bits(chain_info.tip_header.bits)
                            .unwrap_or(1.0);
                    difficulty * 4294967296.0 / 600.0
                } else {
                    0.0
                }
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?;

        // Network stats don't track bytes sent/received at this level
        // These would need to be tracked by NetworkManager
        Ok(NetworkStats {
            peer_count,
            hash_rate,
            bytes_sent: 0,
            bytes_received: 0,
        })
    }

    async fn get_network_peers(&self) -> Result<Vec<PeerInfo>, ModuleError> {
        let network = self.network_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let peer_manager_guard = network.peer_manager().await;

        let mut peers = Vec::new();
        // Access peers via peer_addresses and get_peer
        for transport_addr in peer_manager_guard.peer_addresses() {
            if let Some(peer) = peer_manager_guard.get_peer(&transport_addr) {
                let addr_str = match transport_addr {
                    TransportAddr::Tcp(addr) => addr.to_string(),
                    #[cfg(feature = "quinn")]
                    TransportAddr::Quinn(addr) => addr.to_string(),
                    #[cfg(feature = "iroh")]
                    TransportAddr::Iroh(ref node_id) => format!("iroh:{}", hex::encode(node_id)),
                };

                let transport_type = match transport_addr {
                    TransportAddr::Tcp(_) => "tcp".to_string(),
                    #[cfg(feature = "quinn")]
                    TransportAddr::Quinn(_) => "quinn".to_string(),
                    #[cfg(feature = "iroh")]
                    TransportAddr::Iroh(_) => "iroh".to_string(),
                };

                // Get peer version (stored when version message is received)
                let version = peer.version();

                peers.push(PeerInfo {
                    addr: addr_str,
                    transport_type,
                    services: peer.services(),
                    version,
                    connected_since: peer.conntime(),
                });
            }
        }

        Ok(peers)
    }

    // === Chain API Methods ===
    async fn get_chain_info(&self) -> Result<ChainInfo, ModuleError> {
        // Get chain tip and height
        let tip = self.get_chain_tip().await?;
        let height = self.get_block_height().await?;

        // Get difficulty and chain work from storage
        let (difficulty, chain_work, is_synced) = tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let tip_clone = tip;
            move || {
                // Get tip header to calculate difficulty
                let difficulty = if let Ok(Some(tip_header)) = storage.chain().get_tip_header() {
                    blvm_protocol::pow::difficulty_from_bits(tip_header.bits).unwrap_or(1.0) as u32
                } else {
                    0
                };

                // Get chain work for tip
                let chain_work = storage
                    .chain()
                    .get_chainwork(&tip_clone)
                    .ok()
                    .flatten()
                    .unwrap_or(0) as u64;

                (difficulty, chain_work, true) // Sync status will be checked below
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?;

        // Check sync status from sync coordinator
        let is_synced = if let Some(ref sync_coord) = self.sync_coordinator {
            let sync_guard = sync_coord.lock().await;
            sync_guard.is_synced()
        } else {
            // If sync coordinator not available, assume synced if we have blocks
            height > 0
        };

        Ok(ChainInfo {
            tip_hash: tip,
            height,
            difficulty,
            chain_work,
            is_synced,
        })
    }

    async fn get_block_by_height(&self, height: u64) -> Result<Option<Block>, ModuleError> {
        // Get block hash by height, then get block
        tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            move || {
                storage
                    .blocks()
                    .get_hash_by_height(height)
                    .map_err(|e| ModuleError::op_err("Failed to get hash by height", e))?
                    .and_then(|hash| {
                        storage
                            .blocks()
                            .get_block(&hash)
                            .map_err(|e| ModuleError::op_err("Failed to get block", e))
                            .transpose()
                    })
                    .transpose()
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?
    }

    // === Lightning API Methods ===
    async fn get_lightning_node_url(&self) -> Result<Option<String>, ModuleError> {
        // Query Lightning module storage for node URL
        // Module storage has been removed. Lightning module should use RPC or its own DB.
        Ok(None)
    }

    async fn get_lightning_info(&self) -> Result<Option<LightningInfo>, ModuleError> {
        // Module storage has been removed. Lightning module should use RPC or its own DB.
        Ok(None)
    }

    // === Payment API Methods ===
    async fn get_payment_state(
        &self,
        payment_id: &str,
    ) -> Result<Option<PaymentState>, ModuleError> {
        let payment_state_machine = self.payment_state_machine.as_ref().ok_or_else(|| {
            ModuleError::OperationError(
                module_error_msg::PAYMENT_STATE_MACHINE_NOT_AVAILABLE.to_string(),
            )
        })?;

        match payment_state_machine.get_payment_state(payment_id).await {
            Ok(state) => {
                // Convert internal PaymentState to module API PaymentState
                match state {
                    crate::payment::state_machine::PaymentState::RequestCreated { request_id } => {
                        Ok(Some(PaymentState {
                            payment_id: request_id,
                            status: "pending".to_string(),
                            amount_sats: 0, // Amount not available in this state
                            tx_hash: None,
                            confirmations: None,
                        }))
                    }
                    crate::payment::state_machine::PaymentState::ProofCreated {
                        request_id,
                        ..
                    }
                    | crate::payment::state_machine::PaymentState::ProofBroadcast {
                        request_id,
                        ..
                    } => Ok(Some(PaymentState {
                        payment_id: request_id,
                        status: "pending".to_string(),
                        amount_sats: 0,
                        tx_hash: None,
                        confirmations: None,
                    })),
                    crate::payment::state_machine::PaymentState::InMempool {
                        request_id,
                        tx_hash,
                    } => Ok(Some(PaymentState {
                        payment_id: request_id,
                        status: "pending".to_string(),
                        amount_sats: 0,
                        tx_hash: Some(tx_hash),
                        confirmations: Some(0),
                    })),
                    crate::payment::state_machine::PaymentState::Settled {
                        request_id,
                        tx_hash,
                        confirmation_count,
                        ..
                    } => Ok(Some(PaymentState {
                        payment_id: request_id,
                        status: "confirmed".to_string(),
                        amount_sats: 0,
                        tx_hash: Some(tx_hash),
                        confirmations: Some(confirmation_count),
                    })),
                    crate::payment::state_machine::PaymentState::ReorgPending {
                        request_id,
                        tx_hash,
                        ..
                    } => Ok(Some(PaymentState {
                        payment_id: request_id,
                        status: "reorg_pending".to_string(),
                        amount_sats: 0,
                        tx_hash: Some(tx_hash),
                        confirmations: Some(0),
                    })),
                    crate::payment::state_machine::PaymentState::Failed {
                        request_id,
                        reason: _,
                    } => Ok(Some(PaymentState {
                        payment_id: request_id,
                        status: "failed".to_string(),
                        amount_sats: 0,
                        tx_hash: None,
                        confirmations: None,
                    })),
                }
            }
            Err(_) => Ok(None), // Payment not found
        }
    }

    // === Additional Mempool API Methods ===
    async fn check_transaction_in_mempool(&self, tx_hash: &Hash) -> Result<bool, ModuleError> {
        let mempool = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        Ok(mempool.get_transaction(tx_hash).is_some())
    }

    async fn get_fee_estimate(&self, target_blocks: u32) -> Result<u64, ModuleError> {
        // Check hooks for cached value first
        if let Some(hook_mgr) = &self.hook_manager {
            let hooks = hook_mgr.read().await;
            if let Some(cached_estimate) = hooks.get_fee_estimate_cached(target_blocks).await {
                return Ok(cached_estimate);
            }
        }

        // Fall back to normal calculation
        let mempool = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        // Implement fee estimation algorithm
        // Uses a simple approach: calculate fee rate histogram from mempool
        // and return the fee rate needed for target_blocks confirmation

        let transactions = mempool.get_transactions();
        if transactions.is_empty() {
            // No transactions in mempool, return minimum fee
            return Ok(1);
        }

        // Calculate fee rates for all transactions
        let fee_rates = tokio::task::spawn_blocking({
            let storage = Arc::clone(&self.storage);
            let transactions_clone = transactions.clone();
            move || {
                let mut fee_rates = Vec::new();
                for tx in transactions_clone {
                    // Skip coinbase
                    if tx.inputs.is_empty() {
                        continue;
                    }

                    // Calculate fee
                    let mut input_total = 0u64;
                    for input in &tx.inputs {
                        if let Ok(Some(utxo)) = storage.utxos().get_utxo(&input.prevout) {
                            input_total = input_total.saturating_add(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);

                    // Estimate transaction size (simplified)
                    let mut size = 8; // version + locktime
                    for input in &tx.inputs {
                        size += 36 + input.script_sig.len() + 4; // prevout + script + sequence
                    }
                    for output in &tx.outputs {
                        size += 8 + output.script_pubkey.len(); // value + script
                    }

                    // Calculate fee rate (sat/vbyte)
                    if size > 0 {
                        let fee_rate = fee / size as u64;
                        fee_rates.push(fee_rate);
                    }
                }
                fee_rates
            }
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?;

        let mut fee_rates = fee_rates;
        if fee_rates.is_empty() {
            return Ok(1);
        }

        // Sort fee rates and find the rate needed for target_blocks confirmation
        // Simple approach: use median fee rate, adjusted for target blocks
        fee_rates.sort();
        let median_idx = fee_rates.len() / 2;
        let median_fee_rate = fee_rates[median_idx];

        // Adjust for target blocks (more blocks = lower fee needed)
        // This is a simplified model - real fee estimation uses more sophisticated algorithms
        let adjusted_fee_rate = if target_blocks > 6 {
            median_fee_rate / 2 // Lower fee for longer confirmation time
        } else if target_blocks > 1 {
            median_fee_rate // Standard fee
        } else {
            median_fee_rate * 2 // Higher fee for immediate confirmation
        };

        Ok(adjusted_fee_rate.max(1)) // Minimum 1 sat/vbyte
    }

    async fn register_rpc_endpoint(
        &self,
        method: String,
        description: String,
    ) -> Result<(), ModuleError> {
        let rpc_server = self.rpc_server.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::RPC_SERVER_NOT_AVAILABLE.to_string())
        })?;

        let ipc_server = self.ipc_server.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::IPC_SERVER_NOT_AVAILABLE.to_string())
        })?;

        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        // Get RPC request channel for this module
        let ipc_server_guard = ipc_server.lock().await;
        let rpc_channel = ipc_server_guard
            .get_rpc_channel(&module_id)
            .await
            .ok_or_else(|| {
                ModuleError::OperationError(format!("RPC channel not found for module {module_id}"))
            })?;
        drop(ipc_server_guard);

        // Create IPC-based RPC handler
        let handler = Arc::new(crate::module::rpc::ipc_handler::IpcRpcHandler::new(
            module_id.clone(),
            method.clone(),
            rpc_channel,
        ));

        // Register with RPC server
        rpc_server
            .register_module_endpoint(method.clone(), handler)
            .await
            .map_err(|e| ModuleError::op_err("Failed to register RPC endpoint", e))?;

        Ok(())
    }

    async fn unregister_rpc_endpoint(&self, method: &str) -> Result<(), ModuleError> {
        let rpc_server = self.rpc_server.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::RPC_SERVER_NOT_AVAILABLE.to_string())
        })?;

        rpc_server
            .unregister_module_endpoint(method)
            .await
            .map_err(ModuleError::OperationError)
    }

    async fn register_timer(
        &self,
        interval_seconds: u64,
        callback: Arc<dyn crate::module::timers::manager::TimerCallback>,
    ) -> Result<crate::module::timers::manager::TimerId, ModuleError> {
        let timer_manager = self.timer_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::TIMER_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let module_id = self.module_id_for_timers.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET_FOR_TIMER.to_string())
        })?;

        timer_manager
            .register_timer(module_id.clone(), interval_seconds, callback)
            .await
            .map_err(ModuleError::OperationError)
    }

    async fn cancel_timer(
        &self,
        timer_id: crate::module::timers::manager::TimerId,
    ) -> Result<(), ModuleError> {
        let timer_manager = self.timer_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::TIMER_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        timer_manager
            .cancel_timer(timer_id)
            .await
            .map_err(ModuleError::OperationError)
    }

    async fn schedule_task(
        &self,
        delay_seconds: u64,
        callback: Arc<dyn crate::module::timers::manager::TaskCallback>,
    ) -> Result<crate::module::timers::manager::TaskId, ModuleError> {
        let timer_manager = self.timer_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::TIMER_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let module_id = self.module_id_for_timers.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET_FOR_TASK.to_string())
        })?;

        timer_manager
            .schedule_task(module_id.clone(), delay_seconds, callback)
            .await
            .map_err(ModuleError::OperationError)
    }

    async fn report_metric(&self, metric: Metric) -> Result<(), ModuleError> {
        let metrics_manager = self.metrics_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::METRICS_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let module_id = self.module_id_for_metrics.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET_FOR_METRICS.to_string())
        })?;

        metrics_manager
            .report_metric(module_id.clone(), metric)
            .await;
        Ok(())
    }

    async fn get_module_metrics(&self, module_id: &str) -> Result<Vec<Metric>, ModuleError> {
        let metrics_manager = self.metrics_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::METRICS_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        Ok(metrics_manager.get_module_metrics(module_id).await)
    }

    async fn get_all_metrics(
        &self,
    ) -> Result<std::collections::HashMap<String, Vec<Metric>>, ModuleError> {
        let metrics_manager = self.metrics_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::METRICS_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        Ok(metrics_manager.get_all_metrics().await)
    }

    // === Filesystem API Methods ===
    async fn read_file(&self, path: String) -> Result<Vec<u8>, ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            // Absolute path - validate against sandbox
            sandbox.validate_path(&path)?
        } else {
            // Relative path - join with module data directory
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        tokio::fs::read(&full_path)
            .await
            .map_err(|e| ModuleError::op_err("Failed to read file", e))
    }

    async fn write_file(&self, path: String, data: Vec<u8>) -> Result<(), ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            sandbox.validate_path(&path)?
        } else {
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        // Create parent directory if needed
        if let Some(parent) = full_path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| ModuleError::op_err("Failed to create directory", e))?;
        }

        tokio::fs::write(&full_path, data)
            .await
            .map_err(|e| ModuleError::op_err("Failed to write file", e))
    }

    async fn delete_file(&self, path: String) -> Result<(), ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            sandbox.validate_path(&path)?
        } else {
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        tokio::fs::remove_file(&full_path)
            .await
            .map_err(|e| ModuleError::op_err("Failed to delete file", e))
    }

    async fn list_directory(&self, path: String) -> Result<Vec<String>, ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            sandbox.validate_path(&path)?
        } else {
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        let mut entries = Vec::new();
        let mut dir = tokio::fs::read_dir(&full_path)
            .await
            .map_err(|e| ModuleError::op_err("Failed to read directory", e))?;

        while let Some(entry) = dir
            .next_entry()
            .await
            .map_err(|e| ModuleError::op_err("Failed to read directory entry", e))?
        {
            if let Some(name) = entry.file_name().to_str() {
                entries.push(name.to_string());
            }
        }

        Ok(entries)
    }

    async fn create_directory(&self, path: String) -> Result<(), ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            sandbox.validate_path(&path)?
        } else {
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        tokio::fs::create_dir_all(&full_path)
            .await
            .map_err(|e| ModuleError::op_err("Failed to create directory", e))
    }

    async fn get_file_metadata(
        &self,
        path: String,
    ) -> Result<crate::module::ipc::protocol::FileMetadata, ModuleError> {
        let module_id = self.get_module_id().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ID_NOT_SET.to_string())
        })?;

        let sandbox = {
            let sandboxes = self.module_filesystem_sandboxes.read().await;
            sandboxes
                .get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Filesystem sandbox not initialized for module {module_id}"
                    ))
                })?
                .clone()
        };

        let data_dir = {
            let dirs = self.module_data_dirs.read().await;
            dirs.get(&module_id)
                .ok_or_else(|| {
                    ModuleError::OperationError(format!(
                        "Module data directory not set for module {module_id}"
                    ))
                })?
                .clone()
        };

        // Validate and resolve path
        let full_path = if path.starts_with('/') {
            sandbox.validate_path(&path)?
        } else {
            let joined = data_dir.join(&path);
            sandbox.validate_path(&joined)?
        };

        let metadata = tokio::fs::metadata(&full_path)
            .await
            .map_err(|e| ModuleError::op_err("Failed to get file metadata", e))?;

        let modified = metadata
            .modified()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs());

        let created = metadata
            .created()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs());

        Ok(crate::module::ipc::protocol::FileMetadata {
            path: full_path.to_string_lossy().to_string(),
            size: metadata.len(),
            is_file: metadata.is_file(),
            is_directory: metadata.is_dir(),
            modified,
            created,
        })
    }

    async fn initialize_module(
        &self,
        module_id: String,
        module_data_dir: std::path::PathBuf,
        base_data_dir: std::path::PathBuf,
    ) -> Result<(), ModuleError> {
        // Delegate to the public method
        NodeApiImpl::initialize_module(self, module_id, module_data_dir, base_data_dir).await
    }

    async fn discover_modules(
        &self,
    ) -> Result<Vec<crate::module::traits::ModuleInfo>, ModuleError> {
        let module_manager = self.module_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let manager = module_manager.lock().await;
        let module_info_list = manager.get_all_module_info().await;

        let mut result = Vec::new();
        for (module_id, metadata, state) in module_info_list {
            // Extract module name from module_id (format: {module_name}_{uuid})
            let module_name = module_id
                .split('_')
                .next()
                .unwrap_or(&module_id)
                .to_string();

            result.push(crate::module::traits::ModuleInfo {
                module_id: module_id.clone(),
                module_name: metadata.name.clone(),
                version: metadata.version.clone(),
                capabilities: metadata.capabilities.clone(),
                status: state,
                api_version: 1, // Current API version
            });
        }

        Ok(result)
    }

    async fn get_module_info(
        &self,
        module_id: &str,
    ) -> Result<Option<crate::module::traits::ModuleInfo>, ModuleError> {
        let module_manager = self.module_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let manager = module_manager.lock().await;

        // Try to find by full module_id first
        if let Some(metadata) = manager.get_module_metadata(module_id).await {
            let state = manager
                .get_module_state(module_id)
                .await
                .unwrap_or(crate::module::traits::ModuleState::Stopped);

            // Extract module name from module_id
            let module_name = module_id.split('_').next().unwrap_or(module_id).to_string();

            return Ok(Some(crate::module::traits::ModuleInfo {
                module_id: module_id.to_string(),
                module_name: metadata.name.clone(),
                version: metadata.version.clone(),
                capabilities: metadata.capabilities.clone(),
                status: state,
                api_version: 1,
            }));
        }

        // If not found by full ID, try by module name (first part before _)
        let module_name = module_id.split('_').next().unwrap_or(module_id);
        if let Some(metadata) = manager.get_module_metadata(module_name).await {
            let state = manager
                .get_module_state(module_name)
                .await
                .unwrap_or(crate::module::traits::ModuleState::Stopped);

            // Find the actual module_id (with UUID)
            let modules = manager.list_modules().await;
            let actual_module_id = modules
                .iter()
                .find(|id| id.starts_with(&format!("{module_name}_")))
                .cloned()
                .unwrap_or_else(|| module_id.to_string());

            return Ok(Some(crate::module::traits::ModuleInfo {
                module_id: actual_module_id,
                module_name: metadata.name.clone(),
                version: metadata.version.clone(),
                capabilities: metadata.capabilities.clone(),
                status: state,
                api_version: 1,
            }));
        }

        Ok(None)
    }

    async fn is_module_available(&self, module_id: &str) -> Result<bool, ModuleError> {
        let module_manager = self.module_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let manager = module_manager.lock().await;

        // Check by full module_id
        if manager.get_module_state(module_id).await.is_some() {
            return Ok(true);
        }

        // Check by module name
        let module_name = module_id.split('_').next().unwrap_or(module_id);
        Ok(manager.get_module_state(module_name).await.is_some())
    }

    async fn publish_event(
        &self,
        event_type: EventType,
        payload: EventPayload,
    ) -> Result<(), ModuleError> {
        let event_manager = self.event_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::EVENT_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        event_manager.publish_event(event_type, payload).await
    }

    async fn call_module(
        &self,
        target_module_id: Option<&str>,
        method: &str,
        params: Vec<u8>,
    ) -> Result<Vec<u8>, ModuleError> {
        let router = self.module_router.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_ROUTER_NOT_AVAILABLE.to_string())
        })?;

        // Get caller module ID from instance
        let caller_module_id = self
            .module_id
            .as_ref()
            .or_else(|| self.current_module_id_for_api.as_ref())
            .cloned()
            .unwrap_or_else(|| "unknown".to_string());

        router
            .route_call(&caller_module_id, target_module_id, method, &params)
            .await
    }

    async fn register_module_api(
        &self,
        api: Arc<dyn crate::module::inter_module::api::ModuleAPI>,
    ) -> Result<(), ModuleError> {
        let registry = self.module_api_registry.as_ref().ok_or_else(|| {
            ModuleError::OperationError(
                module_error_msg::MODULE_API_REGISTRY_NOT_AVAILABLE.to_string(),
            )
        })?;

        let module_id = self
            .current_module_id_for_api
            .as_ref()
            .or_else(|| self.module_id.as_ref())
            .ok_or_else(|| {
                ModuleError::OperationError(
                    "Module ID not available for API registration".to_string(),
                )
            })?
            .clone();

        registry.register_api(module_id.clone(), api).await
    }

    async fn unregister_module_api(&self) -> Result<(), ModuleError> {
        let registry = self.module_api_registry.as_ref().ok_or_else(|| {
            ModuleError::OperationError(
                module_error_msg::MODULE_API_REGISTRY_NOT_AVAILABLE.to_string(),
            )
        })?;

        let module_id = self
            .current_module_id_for_api
            .as_ref()
            .or_else(|| self.module_id.as_ref())
            .ok_or_else(|| {
                ModuleError::OperationError(
                    "Module ID not available for API unregistration".to_string(),
                )
            })?
            .clone();

        registry.unregister_api(&module_id).await
    }

    async fn send_mesh_packet_to_module(
        &self,
        module_id: &str,
        packet_data: Vec<u8>,
        peer_addr: String,
    ) -> Result<(), ModuleError> {
        // Use call_module to send mesh packet to the mesh module
        // The mesh module should have a "handle_mesh_packet" method registered
        let params = bincode::serialize(&(packet_data, peer_addr))
            .map_err(|e| ModuleError::SerializationError(e.to_string()))?;

        self.call_module(Some(module_id), "handle_mesh_packet", params)
            .await?;
        Ok(())
    }

    async fn send_mesh_packet_to_peer(
        &self,
        peer_addr: String,
        packet_data: Vec<u8>,
    ) -> Result<(), ModuleError> {
        let network_manager = self.network_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        // Parse peer address (can be SocketAddr string or TransportAddr)
        // Try parsing as SocketAddr first
        if let Ok(socket_addr) = peer_addr.parse::<std::net::SocketAddr>() {
            // Send via SocketAddr
            network_manager
                .send_to_peer(socket_addr, packet_data)
                .await
                .map_err(|e| ModuleError::op_err("Failed to send mesh packet", e))?;
        } else {
            // Try parsing as TransportAddr (format: "tcp:127.0.0.1:8333" or "iroh:...")
            use crate::network::transport::TransportAddr;
            let transport_addr = if let Some(addr_str) = peer_addr.strip_prefix("tcp:") {
                addr_str
                    .parse::<std::net::SocketAddr>()
                    .map(TransportAddr::Tcp)
                    .map_err(|e| ModuleError::op_err("Invalid TCP address", e))?
            } else if peer_addr.starts_with("quinn:") {
                #[cfg(feature = "quinn")]
                {
                    let addr_str = &peer_addr[6..];
                    addr_str
                        .parse::<std::net::SocketAddr>()
                        .map(TransportAddr::Quinn)
                        .map_err(|e| ModuleError::op_err("Invalid Quinn address", e))?
                }
                #[cfg(not(feature = "quinn"))]
                return Err(ModuleError::OperationError(
                    "Quinn transport not enabled".to_string(),
                ));
            } else if peer_addr.starts_with("iroh:") {
                #[cfg(feature = "iroh")]
                {
                    let node_id_str = &peer_addr[5..];
                    let node_id_bytes = hex::decode(node_id_str)
                        .map_err(|e| ModuleError::op_err("Invalid Iroh node ID hex", e))?;
                    if node_id_bytes.len() != 32 {
                        return Err(ModuleError::OperationError(
                            "Iroh node ID must be 32 bytes".to_string(),
                        ));
                    }
                    let mut node_id = [0u8; 32];
                    node_id.copy_from_slice(&node_id_bytes);
                    TransportAddr::Iroh(node_id.to_vec())
                }
                #[cfg(not(feature = "iroh"))]
                return Err(ModuleError::OperationError(
                    "Iroh transport not enabled".to_string(),
                ));
            } else {
                return Err(ModuleError::OperationError(format!(
                    "Invalid peer address format: {peer_addr}"
                )));
            };

            // Send via TransportAddr
            network_manager
                .send_to_peer_by_transport(transport_addr, packet_data)
                .await
                .map_err(|e| ModuleError::op_err("Failed to send mesh packet", e))?;
        }

        Ok(())
    }

    async fn send_stratum_v2_message_to_peer(
        &self,
        peer_addr: String,
        message_data: Vec<u8>,
    ) -> Result<(), ModuleError> {
        let network_manager = self.network_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        // Parse peer address (can be SocketAddr string or TransportAddr)
        // Try parsing as SocketAddr first
        if let Ok(socket_addr) = peer_addr.parse::<std::net::SocketAddr>() {
            // Send via SocketAddr (checks stratum_connections first, then P2P peers)
            #[cfg(feature = "stratum-v2")]
            let result = network_manager
                .send_stratum_v2_to_peer(socket_addr, message_data)
                .await;
            #[cfg(not(feature = "stratum-v2"))]
            let result = network_manager
                .send_to_peer(socket_addr, message_data)
                .await;
            result.map_err(|e| ModuleError::op_err("Failed to send Stratum V2 message", e))?;
        } else {
            // Try parsing as TransportAddr (format: "tcp:127.0.0.1:8333" or "iroh:...")
            use crate::network::transport::TransportAddr;
            let transport_addr = if let Some(addr_str) = peer_addr.strip_prefix("tcp:") {
                addr_str
                    .parse::<std::net::SocketAddr>()
                    .map(TransportAddr::Tcp)
                    .map_err(|e| ModuleError::op_err("Invalid TCP address", e))?
            } else if peer_addr.starts_with("quinn:") {
                #[cfg(feature = "quinn")]
                {
                    let addr_str = &peer_addr[6..];
                    addr_str
                        .parse::<std::net::SocketAddr>()
                        .map(TransportAddr::Quinn)
                        .map_err(|e| ModuleError::op_err("Invalid Quinn address", e))?
                }
                #[cfg(not(feature = "quinn"))]
                return Err(ModuleError::OperationError(
                    "Quinn transport not enabled".to_string(),
                ));
            } else if peer_addr.starts_with("iroh:") {
                #[cfg(feature = "iroh")]
                {
                    let node_id_str = &peer_addr[5..];
                    let node_id_bytes = hex::decode(node_id_str)
                        .map_err(|e| ModuleError::op_err("Invalid Iroh node ID hex", e))?;
                    if node_id_bytes.len() != 32 {
                        return Err(ModuleError::OperationError(
                            "Iroh node ID must be 32 bytes".to_string(),
                        ));
                    }
                    let mut node_id = [0u8; 32];
                    node_id.copy_from_slice(&node_id_bytes);
                    TransportAddr::Iroh(node_id.to_vec())
                }
                #[cfg(not(feature = "iroh"))]
                return Err(ModuleError::OperationError(
                    "Iroh transport not enabled".to_string(),
                ));
            } else {
                return Err(ModuleError::OperationError(format!(
                    "Invalid peer address format: {peer_addr}"
                )));
            };

            // Send via TransportAddr
            network_manager
                .send_to_peer_by_transport(transport_addr, message_data)
                .await
                .map_err(|e| ModuleError::op_err("Failed to send Stratum V2 message", e))?;
        }

        Ok(())
    }

    async fn get_module_health(
        &self,
        module_id: &str,
    ) -> Result<Option<crate::module::process::monitor::ModuleHealth>, ModuleError> {
        let module_manager = self.module_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let manager = module_manager.lock().await;
        // Extract module name from module_id (format: {module_name}_{uuid})
        let module_name = module_id.split('_').next().unwrap_or(module_id);

        // Get module state
        let state = manager.get_module_state(module_name).await;

        // Convert ModuleState to ModuleHealth
        match state {
            Some(ModuleState::Running) => {
                Ok(Some(crate::module::process::monitor::ModuleHealth::Healthy))
            }
            Some(ModuleState::Initializing) => {
                Ok(Some(crate::module::process::monitor::ModuleHealth::Healthy))
            }
            Some(ModuleState::Stopped) => Ok(Some(
                crate::module::process::monitor::ModuleHealth::Unresponsive,
            )),
            Some(ModuleState::Stopping) => Ok(Some(
                crate::module::process::monitor::ModuleHealth::Unresponsive,
            )),
            Some(ModuleState::Error(err)) => Ok(Some(
                crate::module::process::monitor::ModuleHealth::Crashed(err),
            )),
            None => Ok(None),
        }
    }

    async fn get_all_module_health(
        &self,
    ) -> Result<Vec<(String, crate::module::process::monitor::ModuleHealth)>, ModuleError> {
        let module_manager = self.module_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MODULE_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let manager = module_manager.lock().await;
        let modules = manager.list_modules().await;

        let mut result = Vec::new();
        for module_id in modules {
            let module_name = module_id.split('_').next().unwrap_or(&module_id);
            if let Some(state) = manager.get_module_state(module_name).await {
                let health = match state {
                    ModuleState::Running => crate::module::process::monitor::ModuleHealth::Healthy,
                    ModuleState::Initializing => {
                        crate::module::process::monitor::ModuleHealth::Healthy
                    }
                    ModuleState::Stopped => {
                        crate::module::process::monitor::ModuleHealth::Unresponsive
                    }
                    ModuleState::Stopping => {
                        crate::module::process::monitor::ModuleHealth::Unresponsive
                    }
                    ModuleState::Error(err) => {
                        crate::module::process::monitor::ModuleHealth::Crashed(err)
                    }
                };
                result.push((module_id, health));
            }
        }

        Ok(result)
    }

    async fn get_block_template(
        &self,
        rules: Vec<String>,
        coinbase_script: Option<Vec<u8>>,
        coinbase_address: Option<String>,
    ) -> Result<blvm_protocol::mining::BlockTemplate, ModuleError> {
        // Get current height
        let height = self
            .storage
            .chain()
            .get_height()
            .map_err(|e| ModuleError::op_err("Failed to get height", e))?
            .ok_or_else(|| {
                ModuleError::OperationError(module_error_msg::CHAIN_NOT_INITIALIZED.to_string())
            })?;

        // Get tip header
        let prev_header = self
            .storage
            .chain()
            .get_tip_header()
            .map_err(|e| ModuleError::op_err("Failed to get tip header", e))?
            .ok_or_else(|| {
                ModuleError::OperationError(module_error_msg::NO_CHAIN_TIP.to_string())
            })?;

        // Get headers for difficulty adjustment
        let prev_headers = if let Ok(recent) = self.storage.blocks().get_recent_headers(2016) {
            if recent.len() >= 2 {
                recent
            } else {
                // Fallback: get headers by height
                let mut headers = Vec::new();
                if let Ok(Some(current_height)) = self.storage.chain().get_height() {
                    for h in 0..=current_height.min(2015) {
                        if let Ok(Some(hash)) = self.storage.blocks().get_hash_by_height(h) {
                            if let Ok(Some(header)) = self.storage.blocks().get_header(&hash) {
                                headers.push(header);
                            }
                        }
                    }
                }
                headers
            }
        } else {
            Vec::new()
        };

        // Get mempool transactions
        let mempool_manager = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;
        let mempool_txs = mempool_manager.get_transactions();

        // Get UTXO set
        let utxo_set = self
            .storage
            .utxos()
            .get_all_utxos()
            .map_err(|e| ModuleError::op_err("Failed to get UTXO set", e))?;

        // Convert coinbase script/address to ByteString
        // Support "hex:" prefix for raw script bytes (e.g. from DATUM pool payout)
        let coinbase_script_bytes = coinbase_script.unwrap_or_default();
        let coinbase_address_bytes = coinbase_address
            .map(|a| {
                a.strip_prefix("hex:")
                    .map(|h| hex::decode(h).unwrap_or_default())
                    .unwrap_or_else(|| a.into_bytes())
            })
            .unwrap_or_default();

        // Use formally verified consensus function (same as RPC getblocktemplate)
        let template = blvm_protocol::mining::create_block_template(
            &utxo_set,
            &mempool_txs,
            height,
            &prev_header,
            &prev_headers,
            &coinbase_script_bytes,
            &coinbase_address_bytes,
        )
        .map_err(|e| ModuleError::op_err("Template creation failed", e))?;

        Ok(template)
    }

    async fn merge_block_serve_denylist(&self, block_hashes: &[Hash]) -> Result<(), ModuleError> {
        if block_hashes.is_empty() {
            return Ok(());
        }
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.merge_block_serve_denylist(block_hashes);
        Ok(())
    }

    async fn get_block_serve_denylist_snapshot(
        &self,
    ) -> Result<BlockServeDenylistSnapshot, ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        Ok(nm.block_serve_denylist_snapshot())
    }

    async fn clear_block_serve_denylist(&self) -> Result<(), ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.clear_block_serve_denylist();
        Ok(())
    }

    async fn replace_block_serve_denylist(&self, block_hashes: &[Hash]) -> Result<(), ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.replace_block_serve_denylist(block_hashes);
        Ok(())
    }

    async fn merge_tx_serve_denylist(&self, tx_hashes: &[Hash]) -> Result<(), ModuleError> {
        if tx_hashes.is_empty() {
            return Ok(());
        }
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.merge_tx_serve_denylist(tx_hashes);
        Ok(())
    }

    async fn get_tx_serve_denylist_snapshot(&self) -> Result<TxServeDenylistSnapshot, ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        Ok(nm.tx_serve_denylist_snapshot())
    }

    async fn clear_tx_serve_denylist(&self) -> Result<(), ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.clear_tx_serve_denylist();
        Ok(())
    }

    async fn replace_tx_serve_denylist(&self, tx_hashes: &[Hash]) -> Result<(), ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.replace_tx_serve_denylist(tx_hashes);
        Ok(())
    }

    async fn get_sync_status(&self) -> Result<SyncStatus, ModuleError> {
        let Some(ref sc) = self.sync_coordinator else {
            return Err(ModuleError::OperationError(
                "sync coordinator not available".to_string(),
            ));
        };
        let coordinator = sc.lock().await;
        let state = coordinator.current_sync_state();
        let phase = state.as_event_str().to_string();
        let error_message = match &state {
            crate::node::sync::SyncState::Error(s) => Some(s.clone()),
            _ => None,
        };
        Ok(SyncStatus {
            phase,
            progress: coordinator.progress(),
            is_synced: coordinator.is_synced(),
            error_message,
        })
    }

    async fn ban_peer(
        &self,
        peer_addr: &str,
        ban_duration_seconds: Option<u64>,
    ) -> Result<(), ModuleError> {
        let nm = self.network_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string())
        })?;
        let addr: std::net::SocketAddr = peer_addr
            .parse()
            .map_err(|e| ModuleError::OperationError(format!("invalid peer address: {e}")))?;
        let unban_ts = match ban_duration_seconds {
            None => 0u64,
            Some(0) => 0u64,
            Some(secs) => crate::utils::current_timestamp().saturating_add(secs),
        };
        let nm = Arc::clone(nm);
        tokio::task::spawn_blocking(move || {
            nm.ban_peer(addr, unban_ts);
        })
        .await
        .map_err(|e| ModuleError::op_err("Task join error", e))?;
        Ok(())
    }

    async fn set_block_serve_maintenance_mode(&self, enabled: bool) -> Result<(), ModuleError> {
        let Some(nm) = self.network_manager.as_ref() else {
            return Err(ModuleError::OperationError(
                module_error_msg::NETWORK_MANAGER_NOT_AVAILABLE.to_string(),
            ));
        };
        nm.set_block_serve_maintenance_mode(enabled);
        Ok(())
    }

    async fn submit_block(&self, block: Block) -> Result<SubmitBlockResult, ModuleError> {
        use crate::rpc::mining::MiningRpc;
        use serde_json::json;

        // Create MiningRpc instance
        let storage = self.storage.clone();
        let mempool_manager = self.mempool_manager.as_ref().ok_or_else(|| {
            ModuleError::OperationError(module_error_msg::MEMPOOL_MANAGER_NOT_AVAILABLE.to_string())
        })?;

        let mining_rpc = {
            let m = MiningRpc::with_dependencies(storage, mempool_manager.clone());
            match &self.network_manager {
                Some(nm) => m.with_network_manager(Some(Arc::clone(nm))),
                None => m,
            }
        };

        // Serialize block to hex using bincode (same as RPC submitblock)
        let block_bytes = bincode::serialize(&block)
            .map_err(|e| ModuleError::SerializationError(e.to_string()))?;
        let block_hex = hex::encode(block_bytes);

        // Build params
        let params = json!([block_hex]);

        // Call submit_block via RPC method
        let result = mining_rpc
            .submit_block(&params)
            .await
            .map_err(|e| ModuleError::op_err("Failed to submit block", e))?;

        // Parse result
        let result_str = result.as_str().unwrap_or("");
        match result_str {
            "" | "null" => Ok(SubmitBlockResult::Accepted),
            s if s.contains("duplicate") || s.contains("already") => {
                Ok(SubmitBlockResult::Duplicate)
            }
            s => Ok(SubmitBlockResult::Rejected(s.to_string())),
        }
    }

    async fn report_module_health(
        &self,
        health: crate::module::process::monitor::ModuleHealth,
    ) -> Result<(), ModuleError> {
        // Get current module ID
        let module_id = self
            .current_module_id_for_api
            .as_ref()
            .or_else(|| self.module_id.as_ref())
            .ok_or_else(|| {
                ModuleError::OperationError(
                    "Module ID not available for health reporting".to_string(),
                )
            })?
            .clone();

        // Health reporting is handled by ModuleProcessMonitor automatically
        // This method allows modules to self-report additional health information
        debug!("Module {} reported health: {:?}", module_id, health);
        Ok(())
    }
}

// Safety: NodeApiImpl is safe to share across threads (Sync) because:
// - All internal mutable state is protected by Arc, RwLock, or Mutex, ensuring safe concurrent access.
// - The MempoolManager (which contains ZMQ sockets) is already marked as `unsafe impl Sync`.
// - The EventPublisher (which contains ZMQ sockets) is already marked as `unsafe impl Sync`.
// - The NetworkManager (which contains ZMQ sockets) is already marked as `unsafe impl Sync`.
// - All other fields are either Arc-wrapped or are already Sync types.
// This is a workaround for ZMQ's Socket type not being Sync, but the actual usage is safe.
unsafe impl Sync for NodeApiImpl {}