calimero-node-primitives 0.10.0

Core Calimero infrastructure and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
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
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
//! Tests for bundle installation and extraction

use std::fs;

use std::sync::Arc;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use calimero_blobstore::config::BlobStoreConfig;
use calimero_blobstore::{BlobManager, FileSystem};
use calimero_network_primitives::client::NetworkClient;
use calimero_node_primitives::bundle::{
    derive_signer_id_did_key, sign_manifest_json, BundleManifest,
};
use calimero_node_primitives::client::NodeClient;
use calimero_store::db::InMemoryDB;
use calimero_store::Store;
use calimero_utils_actix::LazyRecipient;
use camino::Utf8PathBuf;
use ed25519_dalek::{Signer, SigningKey};
use flate2::write::GzEncoder;
use flate2::Compression;
use futures_util::io::Cursor;
use rand::rngs::OsRng;
use tar::Builder;
use tempfile::TempDir;
use tokio::sync::{broadcast, mpsc};

/// Signs a manifest JSON value and adds the signature field.
/// This is a convenience wrapper around the shared sign_manifest_json function.
fn sign_manifest(manifest_json: &mut serde_json::Value, signing_key: &SigningKey) {
    sign_manifest_json(manifest_json, signing_key).unwrap();
}

/// Create a test bundle archive with manifest.json, app.wasm, abi.json, and migrations
fn create_test_bundle(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_content: &[u8],
    abi_content: Option<&[u8]>,
    migrations: Vec<(&str, &[u8])>,
) -> Utf8PathBuf {
    let bundle_path = temp_dir.path().join(format!("{}-{}.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Generate a signing key for the test bundle
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest.json (without signature initially)
    let mut manifest = BundleManifest {
        version: "1.0".to_string(),
        package: package.to_string(),
        app_version: version.to_string(),
        signer_id: Some(signer_id),
        min_runtime_version: "0.1.0".to_string(),
        metadata: None,
        interfaces: None,
        wasm: Some(calimero_node_primitives::bundle::BundleArtifact {
            path: "app.wasm".to_string(),
            hash: None,
            size: wasm_content.len() as u64,
        }),
        abi: abi_content.map(|content| calimero_node_primitives::bundle::BundleArtifact {
            path: "abi.json".to_string(),
            hash: None,
            size: content.len() as u64,
        }),
        migrations: migrations
            .iter()
            .map(
                |(path, content)| calimero_node_primitives::bundle::BundleArtifact {
                    path: path.to_string(),
                    hash: None,
                    size: content.len() as u64,
                },
            )
            .collect(),
        links: None,
        signature: None,
    };

    // Serialize to JSON value, sign it, then re-serialize
    let mut manifest_json: serde_json::Value = serde_json::to_value(&manifest).unwrap();
    sign_manifest(&mut manifest_json, &signing_key);

    // Note: The manifest struct's signature field is not used after this point
    // since manifest_json is what gets serialized to the bundle. The struct
    // signature field remains None, which is fine since only the JSON is used.

    let manifest_bytes = serde_json::to_vec(&manifest_json).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    // Add ABI file if provided
    if let Some(abi_content) = abi_content {
        let mut abi_header = tar::Header::new_gnu();
        abi_header.set_path("abi.json").unwrap();
        abi_header.set_size(abi_content.len() as u64);
        abi_header.set_cksum();
        tar.append(&abi_header, abi_content).unwrap();
    }

    // Add migrations
    for (path, content) in migrations {
        let mut migration_header = tar::Header::new_gnu();
        migration_header.set_path(path).unwrap();
        migration_header.set_size(content.len() as u64);
        migration_header.set_cksum();
        tar.append(&migration_header, content).unwrap();
    }

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Create a test NodeClient with temporary directories
///
/// The `datastore` parameter allows injecting a custom Store implementation.
/// If `None` is provided, defaults to `InMemoryDB` (no file I/O, faster tests).
async fn create_test_node_client(datastore: Option<Store>) -> (NodeClient, TempDir, TempDir) {
    let data_dir = TempDir::new().unwrap();
    let blob_dir = TempDir::new().unwrap();

    // Default to InMemoryDB if no store is provided (avoids dependency on calimero-store-rocksdb)
    let datastore = datastore.unwrap_or_else(|| Store::new(Arc::new(InMemoryDB::owned())));

    let blobstore = BlobManager::new(
        datastore.clone(),
        FileSystem::new(&BlobStoreConfig::new(
            blob_dir.path().to_path_buf().try_into().unwrap(),
        ))
        .await
        .unwrap(),
    );

    let (event_sender, _) = broadcast::channel(256);
    let (ctx_sync_tx, _) = mpsc::channel(64);

    let node_client = NodeClient::new(
        datastore,
        blobstore,
        NetworkClient::new(LazyRecipient::new()),
        LazyRecipient::new(),
        event_sender,
        ctx_sync_tx,
        String::new(), // Not used in tests
    );

    (node_client, data_dir, blob_dir)
}

#[tokio::test]
async fn test_bundle_detection() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Test single WASM file (should not be detected as bundle)
    let wasm_path = temp_dir.path().join("app.wasm");
    fs::write(&wasm_path, b"wasm content").unwrap();
    let wasm_path_utf8: Utf8PathBuf = wasm_path.try_into().unwrap();

    let result = node_client
        .install_application_from_path(wasm_path_utf8, vec![], None, None)
        .await;
    assert!(result.is_ok(), "Single WASM installation should work");

    // Test bundle file (should be detected as bundle)
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.bundle",
        "1.0.0",
        b"wasm content",
        None,
        vec![],
    );

    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;
    assert!(result.is_ok(), "Bundle installation should work");
}

#[tokio::test]
async fn test_bundle_installation() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create a test bundle
    let wasm_content = b"fake wasm bytecode";
    let abi_content = b"{\"types\": []}";
    let migration1: &[u8] = b"CREATE TABLE test (id INT);";
    let migration2: &[u8] = b"CREATE TABLE users (id INT);";
    let migrations: Vec<(&str, &[u8])> = vec![
        ("migrations/001_init.sql", migration1),
        ("migrations/002_add_users.sql", migration2),
    ];

    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.test",
        "1.0.0",
        wasm_content,
        Some(abi_content),
        migrations.clone(),
    );

    // Install the bundle
    let application_id = node_client
        .install_application_from_path(bundle_path.clone(), vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify application was installed
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist");
    assert!(application.is_some(), "Application should be found");

    // Verify bundle was stored as blob
    let app = application.unwrap();
    let blob_exists = node_client
        .has_blob(&app.blob.bytecode)
        .expect("Should check blob existence");
    assert!(blob_exists, "Bundle blob should exist");

    // Verify extracted files exist
    // Applications are now extracted to node root (parent of blobstore), not blobstore root
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir = node_root
        .join("applications")
        .join("com.example.test")
        .join("1.0.0")
        .join("extracted");

    let wasm_path = extract_dir.join("app.wasm");
    assert!(wasm_path.exists(), "Extracted WASM should exist");

    let abi_path = extract_dir.join("abi.json");
    assert!(abi_path.exists(), "Extracted ABI should exist");

    let migration1_path = extract_dir.join("migrations/001_init.sql");
    assert!(migration1_path.exists(), "First migration should exist");

    let migration2_path = extract_dir.join("migrations/002_add_users.sql");
    assert!(migration2_path.exists(), "Second migration should exist");

    // Verify file contents
    let extracted_wasm = fs::read(&wasm_path).unwrap();
    assert_eq!(extracted_wasm, wasm_content, "WASM content should match");

    let extracted_abi = fs::read(&abi_path).unwrap();
    assert_eq!(extracted_abi, abi_content, "ABI content should match");

    let extracted_migration1 = fs::read(&migration1_path).unwrap();
    assert_eq!(
        extracted_migration1, migrations[0].1,
        "Migration 1 content should match"
    );
}

#[tokio::test]
async fn test_bundle_get_application_bytes() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a test bundle
    let wasm_content = b"fake wasm bytecode for runtime";
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.runtime",
        "2.0.0",
        wasm_content,
        None,
        vec![],
    );

    // Install the bundle
    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Get application bytes (should read from extracted directory)
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes.as_ref(),
        wasm_content,
        "Application bytes should match WASM content"
    );
}

#[tokio::test]
async fn test_bundle_deduplication() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create first bundle with specific WASM content
    let wasm_content_v1 = b"shared wasm bytecode";
    let bundle_path_v1 = create_test_bundle(
        &temp_dir,
        "com.example.shared",
        "1.0.0",
        wasm_content_v1,
        None,
        vec![],
    );

    // Install first version
    let _app_id_v1 = node_client
        .install_application_from_path(bundle_path_v1, vec![], None, None)
        .await
        .expect("First bundle installation should succeed");

    // Create second bundle with same WASM content (should be deduplicated)
    let wasm_content_v2 = wasm_content_v1; // Same content
    let bundle_path_v2 = create_test_bundle(
        &temp_dir,
        "com.example.shared",
        "2.0.0",
        wasm_content_v2,
        None,
        vec![],
    );

    // Install second version
    let _app_id_v2 = node_client
        .install_application_from_path(bundle_path_v2, vec![], None, None)
        .await
        .expect("Second bundle installation should succeed");

    // Check that both versions have the WASM file
    // Applications are now extracted to node root (parent of blobstore), not blobstore root
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir_v1 = node_root
        .join("applications")
        .join("com.example.shared")
        .join("1.0.0")
        .join("extracted");

    let extract_dir_v2 = node_root
        .join("applications")
        .join("com.example.shared")
        .join("2.0.0")
        .join("extracted");

    let wasm_path_v1 = extract_dir_v1.join("app.wasm");
    let wasm_path_v2 = extract_dir_v2.join("app.wasm");

    assert!(wasm_path_v1.exists(), "V1 WASM should exist");
    assert!(wasm_path_v2.exists(), "V2 WASM should exist");

    // Verify both files exist and have the same content
    // (Deduplication may use hardlinks or copies depending on filesystem)
    let content_v1 = fs::read(&wasm_path_v1).unwrap();
    let content_v2 = fs::read(&wasm_path_v2).unwrap();
    assert_eq!(
        content_v1, content_v2,
        "Both versions should have same WASM content"
    );
    assert_eq!(content_v1, wasm_content_v1, "Content should match original");
}

#[tokio::test]
async fn test_bundle_manifest_validation() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle with mismatched package name
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.wrong", // Different package in manifest
        "1.0.0",
        b"wasm",
        None,
        vec![],
    );

    // Install bundle - package/version will be extracted from manifest
    // Since we're extracting from manifest, this test no longer makes sense
    // The package/version will always match because they come from the manifest
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_ok(),
        "Bundle installation should succeed when extracting from manifest"
    );
}

#[tokio::test]
async fn test_bundle_validation_missing_fields() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a bundle with missing package field in manifest
    let bundle_path = temp_dir.path().join("invalid-bundle.mpk");
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Create manifest.json with missing package field
    // Use a raw JSON string to ensure package field is truly missing
    let invalid_manifest_json = r#"{
        "version": "1.0",
        "appVersion": "1.0.0",
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 10
        },
        "migrations": []
    }"#;
    let manifest_json = invalid_manifest_json.as_bytes();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_json.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_json).unwrap();

    // Add a dummy WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(10);
    wasm_header.set_cksum();
    tar.append(&wasm_header, &b"fake wasm"[..]).unwrap();

    tar.finish().unwrap();
    drop(tar); // Ensure tar is dropped and file is flushed
    let bundle_path_utf8: Utf8PathBuf = bundle_path.try_into().unwrap();

    // Installation should fail with validation error
    let result = node_client
        .install_application_from_path(bundle_path_utf8, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail for invalid manifest"
    );
    let error_msg = result.unwrap_err().to_string();
    // BundleManifest deserialization will fail if package field is missing
    // The error could be "missing field 'package'" from serde or "package field is empty" from validation
    // Or it could be a tar parsing error if the archive is malformed
    assert!(
        error_msg.contains("package")
            || error_msg.contains("missing field")
            || error_msg.contains("empty")
            || error_msg.contains("manifest")
            || error_msg.contains("parse"),
        "Error should mention missing package field, manifest issue, or parse error, got: {}",
        error_msg
    );
}

#[tokio::test]
async fn test_bundle_backward_compatibility() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Test that single WASM files still work
    let wasm_path = temp_dir.path().join("app.wasm");
    fs::write(&wasm_path, b"single wasm content").unwrap();
    let wasm_path_utf8: Utf8PathBuf = wasm_path.try_into().unwrap();

    let application_id = node_client
        .install_application_from_path(wasm_path_utf8, vec![], None, None)
        .await
        .expect("Single WASM installation should work");

    // Verify it was installed correctly
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist");
    assert!(
        application.is_some(),
        "Single WASM application should be found"
    );

    // Verify we can get bytes
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(bytes.as_ref(), b"single wasm content", "Bytes should match");
}

/// Create a test bundle with custom WASM path
fn create_test_bundle_custom_wasm_path(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_path: &str,
    wasm_content: &[u8],
) -> Utf8PathBuf {
    let bundle_path = temp_dir.path().join(format!("{}-{}.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Generate a signing key for the test bundle
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest.json with custom WASM path (without signature initially)
    let manifest = BundleManifest {
        version: "1.0".to_string(),
        package: package.to_string(),
        app_version: version.to_string(),
        signer_id: Some(signer_id),
        min_runtime_version: "0.1.0".to_string(),
        metadata: None,
        interfaces: None,
        wasm: Some(calimero_node_primitives::bundle::BundleArtifact {
            path: wasm_path.to_string(),
            hash: None,
            size: wasm_content.len() as u64,
        }),
        abi: None,
        migrations: vec![],
        links: None,
        signature: None,
    };

    // Serialize to JSON value, sign it, then re-serialize
    let mut manifest_json: serde_json::Value = serde_json::to_value(&manifest).unwrap();
    sign_manifest(&mut manifest_json, &signing_key);

    let manifest_bytes = serde_json::to_vec(&manifest_json).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file at custom path
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path(wasm_path).unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

#[tokio::test]
async fn test_bundle_custom_wasm_path() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create bundle with WASM at custom path
    let wasm_content = b"custom path wasm bytecode";
    let bundle_path = create_test_bundle_custom_wasm_path(
        &temp_dir,
        "com.example.custom",
        "1.0.0",
        "src/main.wasm",
        wasm_content,
    );

    // Install the bundle
    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify WASM was extracted at custom path
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir = node_root
        .join("applications")
        .join("com.example.custom")
        .join("1.0.0")
        .join("extracted");
    let wasm_path = extract_dir.join("src/main.wasm");
    assert!(
        wasm_path.exists(),
        "WASM should be extracted at custom path"
    );

    // Verify get_application_bytes reads from custom path
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes.as_ref(),
        wasm_content,
        "Application bytes should match WASM content from custom path"
    );
}

#[tokio::test]
async fn test_bundle_no_metadata() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.metadata",
        "1.0.0",
        b"wasm content",
        None,
        vec![],
    );

    // Install bundle (metadata is extracted from manifest in Registry v2)
    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify metadata contains package and version extracted from manifest
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist")
        .expect("Application should be found");

    // Metadata should contain at least package and version
    assert!(
        !application.metadata.is_empty(),
        "Bundle metadata should contain package and version extracted from manifest"
    );

    // Verify package and version are present
    let metadata_json: serde_json::Value =
        serde_json::from_slice(&application.metadata).expect("Metadata should be valid JSON");
    assert_eq!(
        metadata_json["package"], "com.example.metadata",
        "Package should match manifest"
    );
    assert_eq!(
        metadata_json["version"], "1.0.0",
        "Version should match manifest"
    );
}

#[tokio::test]
async fn test_bundle_validation_empty_package() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle with empty package field
    let bundle_path = temp_dir.path().join("empty-package.mpk");
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    let invalid_manifest_json = r#"{
        "version": "1.0",
        "package": "",
        "appVersion": "1.0.0",
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 10
        },
        "migrations": []
    }"#;
    let manifest_json = invalid_manifest_json.as_bytes();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_json.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_json).unwrap();

    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(10);
    wasm_header.set_cksum();
    tar.append(&wasm_header, &b"fake wasm"[..]).unwrap();

    tar.finish().unwrap();
    drop(tar);
    let bundle_path_utf8: Utf8PathBuf = bundle_path.try_into().unwrap();

    let result = node_client
        .install_application_from_path(bundle_path_utf8, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail for empty package"
    );
    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("package") && error_msg.contains("empty"),
        "Error should mention empty package field, got: {}",
        error_msg
    );
}

#[tokio::test]
async fn test_bundle_validation_empty_app_version() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle with empty appVersion field
    let bundle_path = temp_dir.path().join("empty-version.mpk");
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    let invalid_manifest_json = r#"{
        "version": "1.0",
        "package": "com.example.test",
        "appVersion": "",
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 10
        },
        "migrations": []
    }"#;
    let manifest_json = invalid_manifest_json.as_bytes();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_json.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_json).unwrap();

    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(10);
    wasm_header.set_cksum();
    tar.append(&wasm_header, &b"fake wasm"[..]).unwrap();

    tar.finish().unwrap();
    drop(tar);
    let bundle_path_utf8: Utf8PathBuf = bundle_path.try_into().unwrap();

    let result = node_client
        .install_application_from_path(bundle_path_utf8, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail for empty appVersion"
    );
    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("appVersion") || error_msg.contains("version"),
        "Error should mention empty appVersion field, got: {}",
        error_msg
    );
}

#[tokio::test]
async fn test_bundle_validation_missing_app_version() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle with missing appVersion field
    let bundle_path = temp_dir.path().join("missing-version.mpk");
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    let invalid_manifest_json = r#"{
        "version": "1.0",
        "package": "com.example.test",
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 10
        },
        "migrations": []
    }"#;
    let manifest_json = invalid_manifest_json.as_bytes();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_json.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_json).unwrap();

    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(10);
    wasm_header.set_cksum();
    tar.append(&wasm_header, &b"fake wasm"[..]).unwrap();

    tar.finish().unwrap();
    drop(tar);
    let bundle_path_utf8: Utf8PathBuf = bundle_path.try_into().unwrap();

    let result = node_client
        .install_application_from_path(bundle_path_utf8, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail for missing appVersion"
    );
    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("appVersion")
            || error_msg.contains("missing field")
            || error_msg.contains("version")
            || error_msg.contains("parse"),
        "Error should mention missing appVersion field, got: {}",
        error_msg
    );
}

#[tokio::test]
async fn test_bundle_deduplication_different_paths() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create first bundle with WASM at one path
    let wasm_content = b"shared wasm";
    let bundle_path_v1 = create_test_bundle_custom_wasm_path(
        &temp_dir,
        "com.example.paths",
        "1.0.0",
        "src/app.wasm",
        wasm_content,
    );

    let _app_id_v1 = node_client
        .install_application_from_path(bundle_path_v1, vec![], None, None)
        .await
        .expect("First bundle installation should succeed");

    // Create second bundle with WASM at different path but same content
    let bundle_path_v2 = create_test_bundle_custom_wasm_path(
        &temp_dir,
        "com.example.paths",
        "2.0.0",
        "lib/app.wasm", // Different path
        wasm_content,   // Same content
    );

    let _app_id_v2 = node_client
        .install_application_from_path(bundle_path_v2, vec![], None, None)
        .await
        .expect("Second bundle installation should succeed");

    // Verify both paths exist (should NOT be deduplicated because paths differ)
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir_v1 = node_root
        .join("applications")
        .join("com.example.paths")
        .join("1.0.0")
        .join("extracted");
    let extract_dir_v2 = node_root
        .join("applications")
        .join("com.example.paths")
        .join("2.0.0")
        .join("extracted");

    let wasm_path_v1 = extract_dir_v1.join("src/app.wasm");
    let wasm_path_v2 = extract_dir_v2.join("lib/app.wasm");

    assert!(
        wasm_path_v1.exists(),
        "V1 WASM should exist at src/app.wasm"
    );
    assert!(
        wasm_path_v2.exists(),
        "V2 WASM should exist at lib/app.wasm"
    );

    // Both should have same content but be separate files (not deduplicated due to different paths)
    let content_v1 = fs::read(&wasm_path_v1).unwrap();
    let content_v2 = fs::read(&wasm_path_v2).unwrap();
    assert_eq!(content_v1, content_v2, "Both should have same content");
    assert_eq!(content_v1, wasm_content, "Content should match original");
}

#[tokio::test]
async fn test_bundle_extract_dir_derived_from_manifest() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Install bundle
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.derived",
        "2.5.0",
        b"wasm content",
        None,
        vec![],
    );

    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify metadata contains package and version extracted from manifest
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist")
        .expect("Application should be found");

    // Metadata should contain at least package and version
    assert!(
        !application.metadata.is_empty(),
        "Bundle metadata should contain package and version extracted from manifest"
    );

    // Verify package and version are present
    let metadata_json: serde_json::Value =
        serde_json::from_slice(&application.metadata).expect("Metadata should be valid JSON");
    assert_eq!(
        metadata_json["package"], "com.example.derived",
        "Package should match manifest"
    );
    assert_eq!(
        metadata_json["version"], "2.5.0",
        "Version should match manifest"
    );

    // Verify files were extracted to correct location derived from manifest
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir = node_root
        .join("applications")
        .join("com.example.derived")
        .join("2.5.0")
        .join("extracted");
    assert!(
        extract_dir.exists(),
        "Extract dir should exist at derived path"
    );
}

#[tokio::test]
async fn test_bundle_package_version_extracted_from_manifest() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create bundle with specific package/version
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.extracted",
        "3.7.2",
        b"wasm content",
        None,
        vec![],
    );

    // Install without providing package/version (should extract from manifest)
    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify application metadata has correct package/version from manifest
    let _application = node_client
        .get_application(&application_id)
        .expect("Application should exist")
        .expect("Application should be found");

    // Package/version should be stored in ApplicationMeta (for query functions)
    // We can't directly access ApplicationMeta, but we can verify via list_packages/list_versions
    let packages = node_client.list_packages().expect("Should list packages");
    assert!(
        packages.contains(&"com.example.extracted".to_string()),
        "Package should be listed"
    );

    let versions = node_client
        .list_versions("com.example.extracted")
        .expect("Should list versions");
    assert!(
        versions.contains(&"3.7.2".to_string()),
        "Version should be listed"
    );
}

#[tokio::test]
async fn test_is_bundle_blob() {
    let temp_dir = TempDir::new().unwrap();
    let (_node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a bundle
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.test",
        "1.0.0",
        b"wasm content",
        None,
        vec![],
    );

    // Read bundle bytes
    let bundle_bytes = fs::read(&bundle_path).unwrap();

    // Test bundle detection
    assert!(
        NodeClient::is_bundle_blob(&bundle_bytes),
        "Bundle blob should be detected as bundle"
    );

    // Test non-bundle detection (regular WASM)
    let wasm_bytes = b"fake wasm bytecode";
    assert!(
        !NodeClient::is_bundle_blob(wasm_bytes),
        "Regular WASM should not be detected as bundle"
    );

    // Test non-bundle detection (random bytes)
    let random_bytes = b"random bytes that are not a bundle";
    assert!(
        !NodeClient::is_bundle_blob(random_bytes),
        "Random bytes should not be detected as bundle"
    );
}

#[tokio::test]
async fn test_install_application_from_bundle_blob() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create a bundle
    let wasm_content = b"bundle wasm bytecode";
    let abi_content = b"{\"types\": []}";
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.blob",
        "1.0.0",
        wasm_content,
        Some(abi_content),
        vec![],
    );

    // Read bundle and store as blob (simulating blob sharing)
    let bundle_data = fs::read(&bundle_path).unwrap();
    let cursor = Cursor::new(bundle_data.as_slice());
    let (blob_id, _size) = node_client
        .add_blob(cursor, Some(bundle_data.len() as u64), None)
        .await
        .expect("Should add bundle blob");

    // Install application from bundle blob
    let source = "file:///test/bundle.mpk".parse().unwrap();
    let application_id = node_client
        .install_application_from_bundle_blob(&blob_id, &source)
        .await
        .expect("Should install from bundle blob");

    // Verify application was installed
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist");
    assert!(application.is_some(), "Application should be found");

    // Verify bundle was extracted
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir = node_root
        .join("applications")
        .join("com.example.blob")
        .join("1.0.0")
        .join("extracted");

    let wasm_path = extract_dir.join("app.wasm");
    assert!(wasm_path.exists(), "Extracted WASM should exist");

    let abi_path = extract_dir.join("abi.json");
    assert!(abi_path.exists(), "Extracted ABI should exist");

    // Verify file contents
    let extracted_wasm = fs::read(&wasm_path).unwrap();
    assert_eq!(extracted_wasm, wasm_content, "WASM content should match");

    // Verify we can get application bytes
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes.as_ref(),
        wasm_content,
        "Application bytes should match WASM"
    );
}

#[tokio::test]
async fn test_install_application_from_bundle_blob_no_metadata() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a bundle
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.metadata",
        "1.0.0",
        b"wasm content",
        None,
        vec![],
    );

    // Read bundle and store as blob
    let bundle_data = fs::read(&bundle_path).unwrap();
    let cursor = Cursor::new(bundle_data.as_slice());
    let (blob_id, _size) = node_client
        .add_blob(cursor, Some(bundle_data.len() as u64), None)
        .await
        .expect("Should add bundle blob");

    let source = "file:///test/bundle.mpk".parse().unwrap();
    let application_id = node_client
        .install_application_from_bundle_blob(&blob_id, &source)
        .await
        .expect("Should install from bundle blob without metadata");

    // Verify metadata contains package and version extracted from manifest
    // (Registry v2: metadata is extracted from bundle manifest)
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist")
        .expect("Application should be found");

    // Metadata should contain at least package and version
    assert!(
        !application.metadata.is_empty(),
        "Bundle metadata should contain package and version extracted from manifest"
    );

    // Verify package and version are present
    let metadata_json: serde_json::Value =
        serde_json::from_slice(&application.metadata).expect("Metadata should be valid JSON");
    assert_eq!(
        metadata_json["package"], "com.example.metadata",
        "Package should match manifest"
    );
    assert_eq!(
        metadata_json["version"], "1.0.0",
        "Version should match manifest"
    );
}

#[tokio::test]
async fn test_install_application_from_bundle_blob_missing_blob() {
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a non-existent blob ID
    use calimero_primitives::blobs::BlobId;
    let fake_blob_id = BlobId::from([1; 32]);

    let source = "file:///test/bundle.mpk".parse().unwrap();
    let result = node_client
        .install_application_from_bundle_blob(&fake_blob_id, &source)
        .await;

    assert!(result.is_err(), "Should fail when blob doesn't exist");
    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("not found") || error_msg.contains("fatal"),
        "Error should mention blob not found, got: {}",
        error_msg
    );
}

#[tokio::test]
async fn test_simple_wasm_installation_still_works() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Test that simple WASM installation still works (backward compatibility)
    let wasm_path = temp_dir.path().join("app.wasm");
    fs::write(&wasm_path, b"simple wasm bytecode").unwrap();
    let wasm_path_utf8: Utf8PathBuf = wasm_path.try_into().unwrap();

    let application_id = node_client
        .install_application_from_path(wasm_path_utf8, vec![], None, None)
        .await
        .expect("Single WASM installation should work");

    // Verify it was installed correctly
    let application = node_client
        .get_application(&application_id)
        .expect("Application should exist");
    assert!(
        application.is_some(),
        "Single WASM application should be found"
    );

    // Verify we can get bytes
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes.as_ref(),
        b"simple wasm bytecode",
        "Bytes should match"
    );

    // Verify it's not detected as a bundle
    let app = application.unwrap();
    let blob_bytes = node_client
        .get_blob_bytes(&app.blob.bytecode, None)
        .await
        .expect("Should get blob bytes")
        .expect("Blob bytes should exist");

    assert!(
        !NodeClient::is_bundle_blob(&blob_bytes),
        "Simple WASM should not be detected as bundle"
    );
}

/// Integration test simulating the bundle blob sharing flow:
/// User 1 installs bundle → User 2 receives blob → User 2 installs automatically
///
/// This test verifies that when a bundle blob is shared between nodes,
/// the receiving node can correctly detect and install it, maintaining
/// ApplicationId consistency across nodes.
///
/// NOTE: This test simulates the blob sharing part of the invitation flow.
/// The full invitation flow would require:
/// 1. User 1 installs bundle
/// 2. User 1 creates context with bundle application
/// 3. User 1 invites User 2 (stores context config on external chain/contract)
/// 4. User 2 receives invitation
/// 5. User 2 calls sync_context_config (which fetches context config from external)
/// 6. sync_context_config detects bundle blob exists locally
/// 7. sync_context_config calls install_application_from_bundle_blob
/// 8. User 2 can now use the context
///
/// To test the full flow, we would need to:
/// - Set up ContextClient instances (requires external client mocking)
/// - Mock external config client methods (application(), application_revision(), members_revision(), members())
/// - Simulate context creation and invitation
///
/// The current test verifies the critical integration point: when a bundle blob
/// exists locally, install_application_from_bundle_blob correctly installs it
/// with the same ApplicationId as the original installation.
#[tokio::test]
async fn test_bundle_blob_sharing_integration() {
    let temp_dir = TempDir::new().unwrap();

    // Create User 1's node client
    let (node_client_1, _data_dir_1, _blob_dir_1) = create_test_node_client(None).await;

    // Create User 2's node client (separate instance)
    let (node_client_2, _data_dir_2, blob_dir_2) = create_test_node_client(None).await;

    // Step 1: User 1 installs bundle
    let wasm_content = b"integration test wasm bytecode";
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.integration",
        "1.0.0",
        wasm_content,
        None,
        vec![],
    );

    let application_id_user1 = node_client_1
        .install_application_from_path(bundle_path.clone(), vec![], None, None)
        .await
        .expect("User 1 should install bundle successfully");

    // Verify User 1 has the application
    let app_user1 = node_client_1
        .get_application(&application_id_user1)
        .expect("Application should exist")
        .expect("Application should be found");

    let bundle_blob_id = app_user1.blob.bytecode;
    let bundle_size = app_user1.size;
    let bundle_source = app_user1.source;

    // Step 2: User 2 receives the bundle blob (simulating blob sharing)
    // Read bundle from User 1's blobstore (bundle file was deleted after installation)
    let bundle_data = node_client_1
        .get_blob_bytes(&bundle_blob_id, None)
        .await
        .expect("Should get bundle blob from User 1's blobstore")
        .expect("Bundle blob should exist");
    let cursor = Cursor::new(bundle_data.as_ref());
    let (received_blob_id, received_size) = node_client_2
        .add_blob(cursor, Some(bundle_data.len() as u64), None)
        .await
        .expect("User 2 should receive bundle blob");

    assert_eq!(
        received_blob_id, bundle_blob_id,
        "Received blob ID should match original bundle blob ID"
    );
    assert_eq!(
        received_size, bundle_size,
        "Received blob size should match original bundle size"
    );

    // Step 3: User 2 doesn't have the application yet
    assert!(
        !node_client_2
            .has_application(&application_id_user1)
            .unwrap(),
        "User 2 should not have application before sync"
    );

    // Step 4: Simulate sync_context_config by manually installing from blob
    // This simulates what happens when sync_context_config detects the blob
    // In real scenario, sync_context_config would call install_application_from_bundle_blob
    // No metadata needed - bundle detection happens via is_bundle_blob()
    let application_id_user2 = node_client_2
        .install_application_from_bundle_blob(
            &bundle_blob_id,
            &bundle_source, // Use same source as User 1
        )
        .await
        .expect("User 2 should install from bundle blob");

    // Step 5: Verify ApplicationId consistency
    // Same blob_id + size + source + same metadata (extracted from manifest) = same ApplicationId
    assert_eq!(
        application_id_user1, application_id_user2,
        "ApplicationId should be identical (same blob_id, size, source, and metadata from manifest)"
    );

    // Verify both can access their applications
    let app_user1_final = node_client_1
        .get_application(&application_id_user1)
        .expect("Application should exist")
        .expect("Application should be found");

    let app_user2_final = node_client_2
        .get_application(&application_id_user2)
        .expect("Application should exist")
        .expect("Application should be found");

    // Critical: All fields should match (blob ID, size, source, metadata)
    assert_eq!(
        app_user1_final.blob.bytecode, app_user2_final.blob.bytecode,
        "Blob IDs should be identical (same bundle content)"
    );
    assert_eq!(
        app_user1_final.size, app_user2_final.size,
        "Sizes should be identical"
    );
    assert_eq!(
        app_user1_final.source.to_string(),
        app_user2_final.source.to_string(),
        "Sources should be identical"
    );
    assert_eq!(
        app_user1_final.metadata, app_user2_final.metadata,
        "Metadata should be identical (extracted from same bundle manifest)"
    );

    // Both should have metadata extracted from bundle manifest (Registry v2)
    assert!(
        !app_user1_final.metadata.is_empty(),
        "User 1 should have metadata extracted from bundle manifest"
    );
    assert!(
        !app_user2_final.metadata.is_empty(),
        "User 2 should have metadata extracted from bundle manifest"
    );

    // Verify metadata contains package and version
    let metadata_json: serde_json::Value =
        serde_json::from_slice(&app_user1_final.metadata).expect("Metadata should be valid JSON");
    assert_eq!(
        metadata_json["package"], "com.example.integration",
        "Package should match manifest"
    );
    assert_eq!(
        metadata_json["version"], "1.0.0",
        "Version should match manifest"
    );

    // Step 6: Verify User 2 can get application bytes (WASM)
    let bytes_user2 = node_client_2
        .get_application_bytes(&application_id_user2)
        .await
        .expect("Should get application bytes")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes_user2.as_ref(),
        wasm_content,
        "User 2 should be able to read WASM from bundle"
    );

    // Step 7: Verify bundle was extracted on User 2's node
    let node_root_2 = blob_dir_2.path().parent().unwrap();
    let extract_dir_2 = node_root_2
        .join("applications")
        .join("com.example.integration")
        .join("1.0.0")
        .join("extracted");

    let wasm_path_2 = extract_dir_2.join("app.wasm");
    assert!(
        wasm_path_2.exists(),
        "User 2 should have extracted WASM file"
    );

    let extracted_wasm_2 = fs::read(&wasm_path_2).unwrap();
    assert_eq!(
        extracted_wasm_2, wasm_content,
        "Extracted WASM content should match"
    );
}

// Note: install_application_from_url tests require HTTP/HTTPS URLs and would need
// a mock HTTP server or real server. The URL installation logic is covered by
// integration tests. Path-based installation (which covers the same code paths
// for bundle detection and extraction) is tested below.

// Signature Verification Integration Tests

/// Helper to create an unsigned bundle (no signature field in manifest)
fn create_unsigned_bundle(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_content: &[u8],
) -> Utf8PathBuf {
    let bundle_path = temp_dir
        .path()
        .join(format!("{}-{}-unsigned.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Create manifest.json without signature
    let manifest_json = serde_json::json!({
        "version": "1.0",
        "package": package,
        "appVersion": version,
        "signerId": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": wasm_content.len()
        },
        "migrations": []
        // Note: no "signature" field
    });

    let manifest_bytes = serde_json::to_vec(&manifest_json).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Helper to create a bundle with tampered content (signature was valid at signing,
/// but manifest was modified after signing)
fn create_tampered_bundle(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_content: &[u8],
) -> Utf8PathBuf {
    let bundle_path = temp_dir
        .path()
        .join(format!("{}-{}-tampered.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create the ORIGINAL manifest (what was signed)
    let mut original_manifest = serde_json::json!({
        "version": "1.0",
        "package": package,
        "appVersion": version,
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": wasm_content.len()
        },
        "migrations": []
    });

    // Sign the original manifest
    sign_manifest(&mut original_manifest, &signing_key);

    // Extract the signature we just created
    let signature = original_manifest.get("signature").unwrap().clone();

    // Create a TAMPERED manifest with different appVersion
    let tampered_manifest = serde_json::json!({
        "version": "1.0",
        "package": package,
        "appVersion": "999.999.999",  // TAMPERED!
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": wasm_content.len()
        },
        "migrations": [],
        "signature": signature  // Original signature (won't match tampered content)
    });

    let manifest_bytes = serde_json::to_vec(&tampered_manifest).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Helper to create a bundle where manifest.signerId doesn't match the signing key.
///
/// This manually constructs the mismatch by:
/// 1. Creating a manifest with signerId from key B
/// 2. Signing it with key A (without using sign_manifest_json which would overwrite signerId)
/// 3. The result has signerId B but signature from key A
fn create_signer_id_mismatch_bundle(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_content: &[u8],
) -> Utf8PathBuf {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine;
    use calimero_node_primitives::bundle::{canonicalize_manifest, compute_signing_payload};
    use ed25519_dalek::Signer;

    let bundle_path = temp_dir
        .path()
        .join(format!("{}-{}-signer-mismatch.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    // Generate signing key A (will be used for signing)
    let signing_key_a = SigningKey::generate(&mut OsRng);

    // Generate signing key B (its signerId will be declared in manifest)
    let signing_key_b = SigningKey::generate(&mut OsRng);
    let signer_id_b = derive_signer_id_did_key(signing_key_b.verifying_key().as_bytes());

    // Create manifest that claims signerId from key B
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": package,
        "appVersion": version,
        "signerId": signer_id_b,  // Claims to be signed by key B
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": wasm_content.len()
        },
        "migrations": []
    });

    // Manually sign with key A without overwriting signerId (to create mismatch)
    let canonical_bytes = canonicalize_manifest(&manifest).unwrap();
    let signing_payload = compute_signing_payload(&canonical_bytes);
    let signature = signing_key_a.sign(&signing_payload);

    // Add signature from key A (but signerId is still from key B - mismatch!)
    let public_key_b64 = URL_SAFE_NO_PAD.encode(signing_key_a.verifying_key().as_bytes());
    let signature_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
    manifest.as_object_mut().unwrap().insert(
        "signature".to_string(),
        serde_json::json!({
            "algorithm": "ed25519",
            "publicKey": public_key_b64,
            "signature": signature_b64
        }),
    );

    let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Helper to create a test bundle with a specific signing key (for ApplicationId derivation tests)
fn create_test_bundle_with_key(
    temp_dir: &TempDir,
    package: &str,
    version: &str,
    wasm_content: &[u8],
    signing_key: &SigningKey,
) -> Utf8PathBuf {
    let bundle_path = temp_dir
        .path()
        .join(format!("{}-{}-keyed.mpk", package, version));
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest.json
    let mut manifest_json: serde_json::Value = serde_json::to_value(&BundleManifest {
        version: "1.0".to_string(),
        package: package.to_string(),
        app_version: version.to_string(),
        signer_id: Some(signer_id),
        min_runtime_version: "0.1.0".to_string(),
        metadata: None,
        interfaces: None,
        wasm: Some(calimero_node_primitives::bundle::BundleArtifact {
            path: "app.wasm".to_string(),
            hash: None,
            size: wasm_content.len() as u64,
        }),
        abi: None,
        migrations: vec![],
        links: None,
        signature: None,
    })
    .unwrap();

    // Sign with the provided key
    sign_manifest(&mut manifest_json, signing_key);

    let manifest_bytes = serde_json::to_vec(&manifest_json).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Test: Installation should fail when bundle manifest has no signature field.
///
/// All bundles must be signed. A bundle with a valid manifest
/// but no signature field MUST be rejected during installation.
#[tokio::test]
async fn test_bundle_installation_fails_without_signature() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create an unsigned bundle
    let bundle_path =
        create_unsigned_bundle(&temp_dir, "com.example.unsigned", "1.0.0", b"wasm content");

    // Installation should fail
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail without signature"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("signature") || error_msg.contains("missing"),
        "Error should mention missing signature, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when bundle has been tampered after signing.
///
/// If the manifest content is modified after signing (e.g., appVersion changed),
/// the signature verification MUST fail and installation MUST be rejected.
#[tokio::test]
async fn test_bundle_installation_fails_with_invalid_signature() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a tampered bundle (signed manifest was modified after signing)
    let bundle_path =
        create_tampered_bundle(&temp_dir, "com.example.tampered", "1.0.0", b"wasm content");

    // Installation should fail due to invalid signature
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with tampered content"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("signature") || error_msg.contains("verification"),
        "Error should mention signature verification failure, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when manifest.signerId doesn't match the signing key.
///
/// The signerId in the manifest MUST match the signerId derived from the
/// signature.publicKey. A mismatch indicates the manifest claims a different
/// signing authority than who actually signed it.
#[tokio::test]
async fn test_bundle_installation_fails_signer_id_mismatch() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Create a bundle where signerId doesn't match the signing key
    let bundle_path = create_signer_id_mismatch_bundle(
        &temp_dir,
        "com.example.mismatch",
        "1.0.0",
        b"wasm content",
    );

    // Installation should fail
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with signerId mismatch"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("signerId") || error_msg.contains("mismatch"),
        "Error should mention signerId mismatch, got: {}",
        error_msg
    );
}

/// Test: ApplicationId should be derived from (package, signer_id).
///
/// This verifies that:
/// - Same package + different signers = different ApplicationIds
/// - Same package + same signer + different versions = same ApplicationId
///
/// This ensures cryptographic update authority is enforced: only bundles
/// signed by the same signerId can update the same application.
#[tokio::test]
async fn test_bundle_application_id_derived_from_package_and_signer_id() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate two different signing keys
    let signing_key_s1 = SigningKey::generate(&mut OsRng);
    let signing_key_s2 = SigningKey::generate(&mut OsRng);

    let signer_id_s1 = derive_signer_id_did_key(signing_key_s1.verifying_key().as_bytes());
    let signer_id_s2 = derive_signer_id_did_key(signing_key_s2.verifying_key().as_bytes());

    // Verify the two signerIds are different
    assert_ne!(
        signer_id_s1, signer_id_s2,
        "Test setup: signerIds should be different"
    );

    let package = "com.example.appkey-test";

    // Bundle A: package "com.example.appkey-test", signer S1, version "1.0.0"
    let bundle_a = create_test_bundle_with_key(
        &temp_dir,
        package,
        "1.0.0",
        b"wasm v1 signer1",
        &signing_key_s1,
    );

    let app_id_a = node_client
        .install_application_from_path(bundle_a, vec![], None, None)
        .await
        .expect("Bundle A installation should succeed");

    // Bundle B: package "com.example.appkey-test", signer S2, version "1.0.0"
    // Same package, same version, but DIFFERENT signer
    let bundle_b = create_test_bundle_with_key(
        &temp_dir,
        package,
        "1.0.0-s2", // Slightly different version to avoid storage conflicts
        b"wasm v1 signer2",
        &signing_key_s2,
    );

    let app_id_b = node_client
        .install_application_from_path(bundle_b, vec![], None, None)
        .await
        .expect("Bundle B installation should succeed");

    // Bundle C: package "com.example.appkey-test", signer S1, version "2.0.0"
    // Same package, same signer as A, but DIFFERENT version
    let bundle_c = create_test_bundle_with_key(
        &temp_dir,
        package,
        "2.0.0",
        b"wasm v2 signer1",
        &signing_key_s1,
    );

    let app_id_c = node_client
        .install_application_from_path(bundle_c, vec![], None, None)
        .await
        .expect("Bundle C installation should succeed");

    // ASSERTION 1: app_id_a != app_id_b (different signers = different ApplicationIds)
    // This ensures that applications signed by different authorities are treated
    // as completely different applications, even with the same package name.
    assert_ne!(
        app_id_a, app_id_b,
        "Same package with different signers should produce different ApplicationIds.\n\
         app_id_a (signer S1): {}\n\
         app_id_b (signer S2): {}",
        app_id_a, app_id_b
    );

    // ASSERTION 2: app_id_a == app_id_c (same package + signer = same ApplicationId)
    // Version upgrades for the same AppKey should have the same ApplicationId.
    assert_eq!(
        app_id_a, app_id_c,
        "Same package with same signer should produce same ApplicationId (version upgrade).\n\
         app_id_a (v1.0.0): {}\n\
         app_id_c (v2.0.0): {}",
        app_id_a, app_id_c
    );

    // Verify all applications can be retrieved
    assert!(
        node_client.has_application(&app_id_a).unwrap(),
        "Application A should exist"
    );
    assert!(
        node_client.has_application(&app_id_b).unwrap(),
        "Application B should exist"
    );
    // Note: app_id_c == app_id_a, so it's the same application (version upgrade)

    // Verify the metadata shows the correct package information
    let app_a = node_client
        .get_application(&app_id_a)
        .expect("Should get application A")
        .expect("Application A should exist");

    let app_b = node_client
        .get_application(&app_id_b)
        .expect("Should get application B")
        .expect("Application B should exist");

    let metadata_a: serde_json::Value =
        serde_json::from_slice(&app_a.metadata).expect("Metadata A should be valid JSON");
    let metadata_b: serde_json::Value =
        serde_json::from_slice(&app_b.metadata).expect("Metadata B should be valid JSON");

    // Both should have the same package name
    assert_eq!(
        metadata_a["package"], package,
        "Application A should have correct package"
    );
    assert_eq!(
        metadata_b["package"], package,
        "Application B should have correct package"
    );

    // Note: signerId is stored in ApplicationMeta.signer_id field in the database,
    // not in the metadata JSON blob. The ApplicationId derivation using (package, signer_id)
    // is verified by the assertions above (different signerIds produce different ApplicationIds).
}

#[tokio::test]
async fn test_bundle_get_application_bytes_fallback() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, blob_dir) = create_test_node_client(None).await;

    // Create a test bundle
    let wasm_content = b"fallback test wasm bytecode";
    let bundle_path = create_test_bundle(
        &temp_dir,
        "com.example.fallback",
        "1.0.0",
        wasm_content,
        None,
        vec![],
    );

    // Install the bundle
    let application_id = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await
        .expect("Bundle installation should succeed");

    // Verify extracted WASM exists initially
    let node_root = blob_dir.path().parent().unwrap();
    let extract_dir = node_root
        .join("applications")
        .join("com.example.fallback")
        .join("1.0.0")
        .join("extracted");
    let wasm_path = extract_dir.join("app.wasm");
    assert!(wasm_path.exists(), "Extracted WASM should exist initially");

    // Delete extracted WASM to trigger fallback
    fs::remove_file(&wasm_path).expect("Should delete extracted WASM");
    assert!(!wasm_path.exists(), "WASM should be deleted");

    // Get application bytes - should fallback to re-extract from bundle blob
    // Note: fallback now extracts entire bundle to disk for persistence
    let bytes = node_client
        .get_application_bytes(&application_id)
        .await
        .expect("Should get application bytes via fallback")
        .expect("Application bytes should exist");

    assert_eq!(
        bytes.as_ref(),
        wasm_content,
        "Application bytes should match WASM content (re-extracted from bundle blob)"
    );

    // Verify WASM file now exists (fallback extracts bundle to disk for persistence)
    assert!(
        wasm_path.exists(),
        "WASM file should exist after fallback (fallback extracts bundle to disk)"
    );
}

#[tokio::test]
async fn test_get_latest_version_semantic_ordering() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    let package = "com.example.versioning";

    // Install multiple versions in non-sequential order
    // This tests that semantic version comparison works correctly
    let versions = vec!["1.0.0", "2.0.0", "10.0.0", "1.5.0", "1.10.0", "2.5.0"];

    let mut application_ids = Vec::new();
    for version in &versions {
        let bundle_path =
            create_test_bundle(&temp_dir, package, version, b"wasm content", None, vec![]);

        let app_id = node_client
            .install_application_from_path(bundle_path, vec![], None, None)
            .await
            .expect("Bundle installation should succeed");

        application_ids.push((version.to_string(), app_id));
    }

    // Get latest version - should be "10.0.0" (not "2.5.0" which would be lexicographically latest)
    let (latest_version_str, _latest_app_id) = node_client
        .get_latest_version(package)
        .expect("Should get latest version")
        .expect("Latest version should exist");

    assert_eq!(
        latest_version_str, "10.0.0",
        "Latest version should be 10.0.0 (semantic), not 2.5.0 (lexicographic)"
    );
}

#[tokio::test]
async fn test_get_latest_version_mixed_semver_and_non_semver() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    let package = "com.example.mixed";

    // Install mix of semantic versions and non-semantic versions
    let versions = vec!["1.0.0", "invalid-version", "2.0.0", "also-invalid"];

    let mut application_ids = Vec::new();
    for version in &versions {
        let bundle_path =
            create_test_bundle(&temp_dir, package, version, b"wasm content", None, vec![]);

        let app_id = node_client
            .install_application_from_path(bundle_path, vec![], None, None)
            .await
            .expect("Bundle installation should succeed");

        application_ids.push((version.to_string(), app_id));
    }

    // Get latest version - should prefer semantic versions over non-semantic
    let (latest_version_str, _latest_app_id) = node_client
        .get_latest_version(package)
        .expect("Should get latest version")
        .expect("Latest version should exist");

    // Should be "2.0.0" (latest semantic version), not "invalid-version" or "also-invalid"
    assert_eq!(
        latest_version_str, "2.0.0",
        "Latest version should be 2.0.0 (semantic), preferring semantic versions over non-semantic"
    );
}

// Path Traversal Validation Tests

/// Helper to create a bundle with a custom manifest (for testing malicious inputs)
fn create_bundle_with_custom_manifest(
    temp_dir: &TempDir,
    manifest_json: serde_json::Value,
    wasm_content: &[u8],
) -> Utf8PathBuf {
    let bundle_path = temp_dir.path().join("malicious-bundle.mpk");
    let bundle_file = fs::File::create(&bundle_path).unwrap();
    let encoder = GzEncoder::new(bundle_file, Compression::default());
    let mut tar = Builder::new(encoder);

    let manifest_bytes = serde_json::to_vec(&manifest_json).unwrap();
    let mut manifest_header = tar::Header::new_gnu();
    manifest_header.set_path("manifest.json").unwrap();
    manifest_header.set_size(manifest_bytes.len() as u64);
    manifest_header.set_cksum();
    tar.append(&manifest_header, manifest_bytes.as_slice())
        .unwrap();

    // Add WASM file
    let mut wasm_header = tar::Header::new_gnu();
    wasm_header.set_path("app.wasm").unwrap();
    wasm_header.set_size(wasm_content.len() as u64);
    wasm_header.set_cksum();
    tar.append(&wasm_header, wasm_content).unwrap();

    tar.finish().unwrap();
    bundle_path.try_into().unwrap()
}

/// Test: Installation should fail when package contains path traversal sequence ".."
///
/// A malicious bundle could set package to "../../../etc" to escape the
/// applications directory and write files to arbitrary locations.
#[tokio::test]
async fn test_bundle_validation_path_traversal_in_package() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest with path traversal in package
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": "../../../etc/malicious",  // Path traversal!
        "appVersion": "1.0.0",
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 12
        },
        "migrations": []
    });

    // Sign the manifest
    sign_manifest(&mut manifest, &signing_key);

    let bundle_path = create_bundle_with_custom_manifest(&temp_dir, manifest, b"wasm content");

    // Installation should fail due to path traversal
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with path traversal in package"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("path traversal") || error_msg.contains("'..'"),
        "Error should mention path traversal, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when appVersion contains path traversal sequence ".."
#[tokio::test]
async fn test_bundle_validation_path_traversal_in_version() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest with path traversal in appVersion
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": "com.example.test",
        "appVersion": "../../../tmp/malicious",  // Path traversal!
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 12
        },
        "migrations": []
    });

    // Sign the manifest
    sign_manifest(&mut manifest, &signing_key);

    let bundle_path = create_bundle_with_custom_manifest(&temp_dir, manifest, b"wasm content");

    // Installation should fail due to path traversal
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with path traversal in appVersion"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("path traversal") || error_msg.contains("'..'"),
        "Error should mention path traversal, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when package contains forward slash
#[tokio::test]
async fn test_bundle_validation_forward_slash_in_package() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest with forward slash in package
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": "foo/bar",  // Directory separator!
        "appVersion": "1.0.0",
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 12
        },
        "migrations": []
    });

    // Sign the manifest
    sign_manifest(&mut manifest, &signing_key);

    let bundle_path = create_bundle_with_custom_manifest(&temp_dir, manifest, b"wasm content");

    // Installation should fail due to directory separator
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with forward slash in package"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("directory separator") || error_msg.contains("package"),
        "Error should mention directory separator, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when package contains backslash (Windows path separator)
#[tokio::test]
async fn test_bundle_validation_backslash_in_package() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest with backslash in package
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": "foo\\bar",  // Windows directory separator!
        "appVersion": "1.0.0",
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 12
        },
        "migrations": []
    });

    // Sign the manifest
    sign_manifest(&mut manifest, &signing_key);

    let bundle_path = create_bundle_with_custom_manifest(&temp_dir, manifest, b"wasm content");

    // Installation should fail due to directory separator
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with backslash in package"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("directory separator") || error_msg.contains("package"),
        "Error should mention directory separator, got: {}",
        error_msg
    );
}

/// Test: Installation should fail when package looks like a Windows absolute path
#[tokio::test]
async fn test_bundle_validation_windows_absolute_path_in_package() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Generate a signing key
    let signing_key = SigningKey::generate(&mut OsRng);
    let signer_id = derive_signer_id_did_key(signing_key.verifying_key().as_bytes());

    // Create manifest with Windows absolute path in package
    let mut manifest = serde_json::json!({
        "version": "1.0",
        "package": "C:malicious",  // Windows absolute path!
        "appVersion": "1.0.0",
        "signerId": signer_id,
        "minRuntimeVersion": "0.1.0",
        "wasm": {
            "path": "app.wasm",
            "size": 12
        },
        "migrations": []
    });

    // Sign the manifest
    sign_manifest(&mut manifest, &signing_key);

    let bundle_path = create_bundle_with_custom_manifest(&temp_dir, manifest, b"wasm content");

    // Installation should fail due to absolute path
    let result = node_client
        .install_application_from_path(bundle_path, vec![], None, None)
        .await;

    assert!(
        result.is_err(),
        "Bundle installation should fail with Windows absolute path in package"
    );

    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("absolute path") || error_msg.contains("package"),
        "Error should mention absolute path, got: {}",
        error_msg
    );
}

/// Test: Valid package names should be accepted
#[tokio::test]
async fn test_bundle_validation_valid_package_names() {
    let temp_dir = TempDir::new().unwrap();
    let (node_client, _data_dir, _blob_dir) = create_test_node_client(None).await;

    // Test various valid package name formats
    let valid_packages = vec![
        "com.example.myapp",
        "my-app",
        "my_app_v2",
        "MyApp",
        "app123",
        "com.calimero.kv-store",
    ];

    for (i, package) in valid_packages.iter().enumerate() {
        let bundle_path = create_test_bundle(
            &temp_dir,
            package,
            &format!("1.0.{}", i), // Unique version to avoid conflicts
            b"wasm content",
            None,
            vec![],
        );

        let result = node_client
            .install_application_from_path(bundle_path, vec![], None, None)
            .await;

        assert!(
            result.is_ok(),
            "Bundle with valid package '{}' should install successfully, got error: {:?}",
            package,
            result.err()
        );
    }
}