c2pa 0.91.9

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
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
// Copyright 2022 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use std::{
    collections::{HashMap, HashSet},
    io::Cursor,
};

use async_generic::async_generic;

use crate::{
    assertion::{Assertion, AssertionBase, AssertionData, AssertionDecodeError},
    assertions::{
        labels::{self, CLAIM},
        DataBox, Ingredient, Relationship, User, UserCbor,
    },
    claim::{Claim, ClaimAssertion},
    context::{Context, ProgressPhase},
    crypto::{
        cose::{CertificateTrustPolicy, TrustAnchorType},
        hash::sha256,
    },
    dynamic_assertion::{
        AsyncDynamicAssertion, DynamicAssertion, DynamicAssertionContent, PartialClaim,
    },
    error::{Error, Result},
    hash_utils::{hash_by_alg, vec_compare},
    hashed_uri::HashedUri,
    jumbf::{
        self,
        boxes::*,
        c2pa_encoding::{build_assertion_box, build_signature_box},
        labels::{
            assertion_label_from_uri, manifest_label_from_uri, manifest_label_to_parts,
            to_assertion_uri, ASSERTIONS, CREDENTIALS, DATABOXES, SIGNATURE,
        },
    },
    log_item,
    manifest_store_report::ManifestStoreReport,
    settings::{get_thread_local_settings, TrustListKind, MAX_ASSERTIONS},
    status_tracker::{ErrorBehavior, StatusTracker},
    store::{InvalidClaimError, StoreValidationInfo},
    utils::is_zero,
    validation_results::validation_codes::{
        ASSERTION_CBOR_INVALID, ASSERTION_JSON_INVALID, ASSERTION_MISSING, CLAIM_MALFORMED,
    },
    validation_status::{self, ALGORITHM_UNSUPPORTED},
    AsyncSigner, Signer,
};

pub(super) const MANIFEST_STORE_EXT: &str = "c2pa"; // file extension for external manifests

/// Maximum depth of nested ingredient references allowed during validation.
///
/// Prevents stack overflow when processing a manifest store that contains a deep
/// linear chain of ingredient references (A → B → C → … → N). With the default
/// 8 MB thread stack, ~3 000 levels causes an unrecoverable stack overflow (exit 134).
/// A limit of 200 uses only ~540 KB of stack, providing a large safety margin while
/// accommodating any realistic provenance chain depth.
///
/// Bounds path length only: independent of the `visited` memoization in `ingredient_checks`.
/// A shared-subtree DAG can have short paths yet exponentially many paths through it.
pub(super) const MAX_INGREDIENT_DEPTH: usize = 200;

pub(crate) struct ManifestHashes {
    pub manifest_box_hash: Vec<u8>,
    pub signature_box_hash: Vec<u8>,
}

/// A `Store` maintains a list of `Claim` structs.
///
/// Typically, this list of `Claim`s represents all of the claims in an asset.
#[derive(Debug)]
pub struct Store {
    claims_map: HashMap<String, Claim>,
    pub(super) claims: Vec<String>, // maintains order of claims
    manifest_box_hash_cache: HashMap<String, (Vec<u8>, Vec<u8>)>,
    pub(super) label: String,
    pub(super) provenance_path: Option<String>,
    pub(super) ctp: CertificateTrustPolicy,
    pub(super) remote_url: Option<String>,
    pub(super) embedded: bool,
}

struct ManifestInfo<'a> {
    pub desc_box: &'a JUMBFDescriptionBox,
    pub sbox: &'a JUMBFSuperBox,
}

impl Default for Store {
    fn default() -> Self {
        Self::from_context(&Context::new())
    }
}

impl Store {
    /// Create a new, empty claims store with default settings.
    pub fn new() -> Self {
        Store {
            claims_map: HashMap::new(),
            manifest_box_hash_cache: HashMap::new(),
            claims: Vec::new(),
            label: MANIFEST_STORE_EXT.to_string(),
            ctp: CertificateTrustPolicy::default(),
            provenance_path: None,
            remote_url: None,
            embedded: false,
        }
    }

    /// Create a new, empty claims store with the specified settings.
    pub fn from_context(context: &Context) -> Self {
        let mut store = Store::new();
        let settings = context.settings();

        // use the incoming trust settings
        store.ctp.clear();

        // Add all of the trust anchors
        if let Some(anchors) = &settings.trust.anchors {
            for anchor in anchors {
                let trust_list_uri = match &anchor.trust_uri {
                    Some(uri) => uri.to_string(),
                    None => format!(
                        "https://c2pa-rs/unknown_trust_list_{}",
                        extfmt::Hexlify(&hash_by_alg(
                            "sha256",
                            anchor.trust_anchors.as_bytes(),
                            None
                        ))
                    ),
                };

                let trust_list_type = match anchor.trust_kind {
                    TrustListKind::Manifest => TrustAnchorType::Manifest,
                    TrustListKind::TSA => TrustAnchorType::TSA,
                    TrustListKind::CAWG => TrustAnchorType::CAWG,
                };

                // Anchors are pre-validated when loading the settings
                let _v = store.add_trust_anchor(
                    anchor.trust_anchors.as_bytes(),
                    &trust_list_uri,
                    trust_list_type,
                    anchor.trust_config.clone(),
                );

                if let Some(al) = &anchor.allowed_list {
                    let _v = store.add_trust_allowed_list(al.as_bytes());
                }
            }
        }

        if let Some(tc) = &settings.trust.trust_config {
            let _v = store.add_trust_config(tc.as_bytes());
        }

        store
    }

    // Append new Store to the current Store preserving the order from the new Store
    pub(crate) fn append_store(&mut self, store: &Store) {
        for claim in store.claims() {
            self.insert_restored_claim(claim.label().to_string(), claim.clone());
        }
    }

    /// Return label for the store
    #[allow(dead_code)] // doesn't harm to have this
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns the remote url of the manifest if this [`Store`] was obtained remotely.
    pub fn remote_url(&self) -> Option<&str> {
        self.remote_url.as_deref()
    }

    /// Returns if the [`Store`] was created from an embedded manifest.
    pub fn is_embedded(&self) -> bool {
        self.embedded
    }

    /// Load named trust anchor sets. [u8] containing the
    /// trust anchors is passed in the trust_vec variable.  The trust_list_uri
    /// is the URI of the trust list per C2PA specification. The TrustAnchorType
    /// indicates the intended use.  trust_config is an optional byte array containing
    /// the trust configuration data for this trust list.
    pub fn add_trust_anchor(
        &mut self,
        trust_vec: &[u8],
        trust_list_uri: &str,
        trust_list_type: TrustAnchorType,
        trust_config: Option<String>,
    ) -> Result<()> {
        Ok(self
            .ctp
            .add_trust_anchors(trust_vec, trust_list_uri, trust_list_type, trust_config)?)
    }

    pub fn add_trust_config(&mut self, trust_vec: &[u8]) -> Result<()> {
        self.ctp.add_valid_ekus(trust_vec);
        Ok(())
    }

    pub fn add_trust_allowed_list(&mut self, allowed_vec: &[u8]) -> Result<()> {
        Ok(self.ctp.add_end_entity_credentials(allowed_vec)?)
    }

    /// Get the provenance if available.
    /// If loaded from an existing asset it will be provenance from the last claim.
    /// If a new claim is committed that will be the provenance claim
    pub fn provenance_path(&self) -> Option<String> {
        self.provenance_path.as_ref().cloned()
    }

    // set the path of the current provenance claim
    pub fn set_provenance_path(&mut self, claim: &Claim) {
        let path = claim.to_claim_uri();
        self.provenance_path = Some(path);
    }

    /// get the list of claims for this store in the order they were added
    pub fn claims(&self) -> Vec<&Claim> {
        self.claims
            .iter()
            .filter_map(|l| self.claims_map.get(l))
            .collect()
    }

    /// the JUMBF manifest box hash (spec 1.2) and signature box hash (2.x)
    pub(crate) fn get_manifest_box_hashes(&self, claim: &Claim) -> ManifestHashes {
        if let Some((mbh, sbh)) = self.manifest_box_hash_cache.get(claim.label()) {
            ManifestHashes {
                manifest_box_hash: mbh.clone(),
                signature_box_hash: sbh.clone(),
            }
        } else {
            ManifestHashes {
                manifest_box_hash: Store::calc_manifest_box_hash(claim, None, claim.alg())
                    .unwrap_or_default(),
                signature_box_hash: Claim::calc_sig_box_hash(claim, claim.alg())
                    .unwrap_or_default(),
            }
        }
    }

    // remove a claim from the store
    pub(crate) fn remove_claim(&mut self, label: &str) -> Option<Claim> {
        self.claims.retain(|l| l != label);
        self.claims_map.remove(label)
    }

    /// Add a new Claim to this Store. The function
    /// will return the label of the claim.
    pub fn commit_claim(&mut self, mut claim: Claim) -> Result<String> {
        // make sure there is no pending unsigned claim
        if let Some(pc) = self.provenance_claim() {
            if pc.signature_val().is_empty() {
                return Err(Error::ClaimUnsigned);
            }
        }
        // verify the claim is valid
        claim.build()?;

        // update the provenance path
        self.set_provenance_path(&claim);

        let claim_label = claim.label().to_string();

        // add ingredients claims to the store claims
        // replace any existing claims with the same label
        for ingredient in claim.claim_ingredients() {
            if self
                .claims_map
                .insert(ingredient.label().to_string(), ingredient.clone())
                .is_none()
            {
                self.claims.push(ingredient.label().to_string());
            }
        }

        // add to new claim to list of claims
        self.claims.push(claim_label.clone());
        self.claims_map.insert(claim_label.clone(), claim);

        Ok(claim_label)
    }

    /// Add a new update manifest to this Store. The manifest label
    /// may be updated to reflect is position in the manifest Store
    /// if there are conflicting label names.  The function
    /// will return the label of the claim used
    #[allow(unused)]
    pub fn update_manifest_test(&mut self, claim: &Claim) -> Result<()> {
        use crate::{
            assertions::{labels::CLAIM_THUMBNAIL, Actions},
            claim::ALLOWED_UPDATE_MANIFEST_ACTIONS,
        };

        // check for disallowed assertions
        if claim.has_assertion_type(labels::DATA_HASH)
            || claim.has_assertion_type(labels::BOX_HASH)
            || claim.has_assertion_type(labels::BMFF_HASH)
            || claim.has_assertion_type(labels::COLLECTION_HASH)
        {
            return Err(Error::ClaimInvalidContent);
        }

        // must have exactly one ingredient
        let ingredient_assertions = claim.ingredient_assertions();
        if ingredient_assertions.len() != 1 {
            return Err(Error::ClaimInvalidContent);
        }

        let ingredient = Ingredient::from_assertion(ingredient_assertions[0].assertion())?;

        // must have a parent relationship
        if ingredient.relationship != Relationship::ParentOf {
            return Err(Error::IngredientNotFound);
        }

        // make sure ingredient c2pa.manifest points to provenance claim
        if let Some(c2pa_manifest) = ingredient.c2pa_manifest() {
            // the manifest should refer to provenance claim
            if let Some(pc) = self.provenance_claim() {
                if !c2pa_manifest.url().contains(pc.label()) {
                    return Err(Error::IngredientNotFound);
                }
            } else {
                // when called from builder, there will be no provenance claim yet
                // so we cannot verify the manifest url, but we just created it.
                // return Err(Error::IngredientNotFound);
            }
        } else {
            return Err(Error::IngredientNotFound);
        }

        // must be one of the allowed actions
        for aa in claim.action_assertions() {
            let actions = Actions::from_assertion(aa.assertion())?;
            for action in actions.actions() {
                if !ALLOWED_UPDATE_MANIFEST_ACTIONS
                    .iter()
                    .any(|a| *a == action.action())
                {
                    return Err(Error::ClaimInvalidContent);
                }
            }
        }

        // thumbnail assertions are not allowed
        if claim
            .claim_assertion_store()
            .iter()
            .any(|ca| ca.label_raw().contains(CLAIM_THUMBNAIL))
        {
            return Err(Error::OtherError(
                "only one claim thumbnail assertion allowed".into(),
            ));
        }

        Ok(())
    }

    /// Add a new update manifest to this Store. The manifest label
    /// may be updated to reflect is position in the manifest Store
    /// if there are conflicting label names.  The function
    /// will return the label of the claim used
    #[allow(unused)]
    pub fn commit_update_manifest(&mut self, mut claim: Claim) -> Result<String> {
        self.update_manifest_test(&claim)?;

        claim.set_update_manifest(true);

        self.commit_claim(claim)
    }

    /// Get Claim by label
    // Returns Option<&Claim>
    pub fn get_claim(&self, label: &str) -> Option<&Claim> {
        self.claims_map.get(label)
    }

    /// Returns true if `uri` (absolute or relative to `claim_label`) appears in the
    /// redaction list of any claim in the store — i.e. it was intentionally removed
    /// by a parent manifest.
    pub(crate) fn is_uri_redacted(&self, claim_label: &str, uri: &str) -> bool {
        let abs_uri = jumbf::labels::to_absolute_uri(claim_label, uri);
        self.claims_map
            .values()
            .any(|c| c.redactions().is_some_and(|r| r.contains(&abs_uri)))
    }

    /// Get Claim by label
    // Returns Option<&Claim>
    pub fn get_claim_mut(&mut self, label: &str) -> Option<&mut Claim> {
        self.claims_map.get_mut(label)
    }

    /// returns a Claim given a jumbf uri
    pub fn get_claim_from_uri(&self, uri: &str) -> Result<&Claim> {
        let claim_label = Store::manifest_label_from_path(uri);
        self.get_claim(&claim_label)
            .ok_or_else(|| Error::ClaimMissing {
                label: claim_label.to_owned(),
            })
    }

    /// returns a ClaimAssertion given a jumbf uri, resolving to the right claim in the store
    pub fn get_claim_assertion_from_uri(&self, uri: &str) -> Result<&ClaimAssertion> {
        // first find the right claim and then look for the assertion there
        let claim = self.get_claim_from_uri(uri)?;
        let (label, instance) = Claim::assertion_label_from_link(uri);
        claim
            .get_claim_assertion(&label, instance)
            .ok_or_else(|| Error::AssertionMissing {
                url: uri.to_owned(),
            })
    }

    /// Returns an Assertion referenced by JUMBF URI.  The URI should be absolute and include
    /// the desired Claim in the path. If you need to specify the Claim for this URI use
    /// get_assertion_from_uri_and_claim.
    /// uri - The JUMBF URI for desired Assertion.
    pub fn get_assertion_from_uri(&self, uri: &str) -> Option<&Assertion> {
        let claim_label = Store::manifest_label_from_path(uri);
        let (assertion_label, instance) = Claim::assertion_label_from_link(uri);

        if let Some(claim) = self.get_claim(&claim_label) {
            claim.get_assertion(&assertion_label, instance)
        } else {
            None
        }
    }

    /// Returns an Assertion referenced by JUMBF URI. Only the Claim specified by target_claim_label
    /// will be searched.  The target_claim_label can be a Claim label or JUMBF URI.
    /// uri - The JUMBF URI for desired Assertion.
    /// target_claim_label - Label or URI of the Claim to search for the case when the URI is a relative path.
    pub fn get_assertion_from_uri_and_claim(
        &self,
        uri: &str,
        target_claim_label: &str,
    ) -> Option<&Assertion> {
        let (assertion_label, instance) = Claim::assertion_label_from_link(uri);

        let label = Store::manifest_label_from_path(target_claim_label);

        if let Some(claim) = self.get_claim(&label) {
            claim.get_assertion(&assertion_label, instance)
        } else {
            None
        }
    }

    /// Returns a DataBox referenced by JUMBF URI if it exists.
    ///
    /// Relative paths will use the provenance claim to resolve the DataBox.d
    pub fn get_data_box_from_uri_and_claim(
        &self,
        hr: &HashedUri,
        target_claim_label: &str,
    ) -> Option<&DataBox> {
        match jumbf::labels::manifest_label_from_uri(&hr.url()) {
            Some(label) => self.get_claim(&label), // use the manifest label from the thumbnail uri
            None => self.get_claim(target_claim_label), //  relative so use the target claim label
        }
        .and_then(|claim| claim.get_databox(hr))
    }

    // Returns placeholder that will be searched for and replaced
    // with actual signature data.
    fn sign_claim_placeholder(claim: &Claim, min_reserve_size: usize) -> Vec<u8> {
        let placeholder_str = format!("signature placeholder:{}", claim.label());
        let mut placeholder = sha256(placeholder_str.as_bytes());

        use std::cmp::max;
        placeholder.resize(max(placeholder.len(), min_reserve_size), 0);

        placeholder
    }

    /// return the current provenance claim label if available
    pub fn provenance_label(&self) -> Option<String> {
        self.provenance_path()
            .map(|provenance| Store::manifest_label_from_path(&provenance))
    }

    /// return the current provenance claim if available
    pub fn provenance_claim(&self) -> Option<&Claim> {
        match self.provenance_path() {
            Some(provenance) => {
                let claim_label = Store::manifest_label_from_path(&provenance);
                self.get_claim(&claim_label)
            }
            None => None,
        }
    }

    /// return the current provenance claim as mutable if available
    pub fn provenance_claim_mut(&mut self) -> Option<&mut Claim> {
        match self.provenance_path() {
            Some(provenance) => {
                let claim_label = Store::manifest_label_from_path(&provenance);
                self.get_claim_mut(&claim_label)
            }
            None => None,
        }
    }

    // add a restored claim
    pub(crate) fn insert_restored_claim(&mut self, label: String, claim: Claim) {
        self.set_provenance_path(&claim);
        self.claims_map.insert(label.clone(), claim);
        self.claims.push(label);
    }

    /// Build a flat ingredient [`Store`] for `claim` by walking nested ingredient assertions.
    ///
    /// Used to materialize the JUMBF bytes for a single ingredient's provenance chain without
    /// eagerly serializing every ingredient when constructing a [`Reader`](crate::Reader).
    pub(crate) fn build_flat_ingredient_store(store: &Store, claim: &Claim) -> Result<Store> {
        let mut ingredient_store = Store::new();
        let mut visited = HashSet::new();
        let mut path = Vec::new();

        fn collect_flat(
            store: &Store,
            claim: &Claim,
            ingredient_store: &mut Store,
            visited: &mut HashSet<String>,
            path: &mut Vec<String>,
        ) -> Result<()> {
            let claim_label = claim.label().to_string();

            if visited.contains(&claim_label) {
                return Ok(());
            }

            // Cycle detection
            if path.iter().any(|p| p == &claim_label) {
                return Ok(());
            }

            path.push(claim_label.clone());

            for ing_assertion in claim.ingredient_assertions() {
                let ingredient = Ingredient::from_assertion(ing_assertion.assertion())?;
                let manifest_uri = ingredient
                    .active_manifest
                    .as_ref()
                    .or(ingredient.c2pa_manifest.as_ref());
                if let Some(manifest_uri) = manifest_uri {
                    let ingredient_label = Store::manifest_label_from_path(&manifest_uri.url());
                    if let Some(ingredient_claim) = store.get_claim(&ingredient_label) {
                        collect_flat(store, ingredient_claim, ingredient_store, visited, path)?;
                    }
                }
            }

            // Post-order: add after all children
            ingredient_store.insert_restored_claim(claim_label.clone(), claim.clone());
            visited.insert(claim_label);
            path.pop();

            Ok(())
        }

        collect_flat(store, claim, &mut ingredient_store, &mut visited, &mut path)?;

        Ok(ingredient_store)
    }

    // replace a claim if it already exists
    pub(crate) fn replace_claim_or_insert(&mut self, label: String, claim: Claim) {
        if self.get_claim(&label).is_some() {
            self.claims_map.insert(label.clone(), claim);
        } else {
            self.insert_restored_claim(label, claim);
        }
    }

    fn add_assertion_to_jumbf_store(
        store: &mut CAIAssertionStore,
        claim_assertion: &ClaimAssertion,
    ) -> Result<()> {
        let assertion_box = build_assertion_box(
            &claim_assertion.label(),
            claim_assertion.assertion(),
            claim_assertion.salt().clone(),
        )?;
        store.add_assertion(assertion_box.into_box());
        Ok(())
    }

    // look for old style hashing to determine if this is a pre 1.0 claim
    fn is_old_assertion(alg: &str, data: &[u8], original_hash: &[u8]) -> bool {
        let old_hash = hash_by_alg(alg, data, None);
        vec_compare(&old_hash, original_hash)
    }

    fn get_assertion_from_jumbf_store(
        claim: &Claim,
        assertion_box: &JUMBFSuperBox,
        label: &str,
        check_for_legacy_assertion: bool,
        validation_log: &mut StatusTracker,
    ) -> Result<ClaimAssertion> {
        let assertion_desc_box = assertion_box.desc_box();

        let (raw_label, instance) = Claim::assertion_label_from_link(label);
        let instance_label = Claim::label_with_instance(&raw_label, instance);
        let (assertion_hashed_uri, claim_assertion_type) = claim
            .assertion_hashed_uri_from_label(&instance_label)
            .ok_or_else(|| {
                log_item!(
                    label.to_owned(),
                    "error loading assertion",
                    "get_assertion_from_jumbf_store"
                )
                .validation_status(ASSERTION_MISSING)
                .failure_as_err(
                    validation_log,
                    Error::AssertionMissing {
                        url: instance_label.to_string(),
                    },
                )
            })?;

        let alg = match assertion_hashed_uri.alg() {
            Some(ref a) => a.clone(),
            None => claim.alg().to_string(),
        };

        // get salt value if set
        let salt = assertion_desc_box.get_salt();

        let result = match assertion_desc_box.uuid().as_ref() {
            CAI_JSON_ASSERTION_UUID => {
                let json_box = assertion_box
                    .data_box_as_json_box(0)
                    .ok_or(Error::JumbfBoxNotFound)?;

                let assertion = Assertion::from_data_json(&raw_label, json_box.json())?;

                // make sure it is JSON
                if let Err(e) = serde_json::from_slice::<serde_json::Value>(json_box.json()) {
                    log_item!(
                        label.to_owned(),
                        "invalid assertion json",
                        "get_assertion_from_jumbf_store"
                    )
                    .validation_status(ASSERTION_JSON_INVALID)
                    .failure(
                        validation_log,
                        Error::AssertionDecoding(
                            AssertionDecodeError::from_assertion_and_json_err(&assertion, e),
                        ),
                    )?;
                }

                let hash = Claim::calc_assertion_box_hash(label, &assertion, salt.clone(), &alg)?;
                Ok(ClaimAssertion::new(
                    assertion,
                    instance,
                    &hash,
                    &alg,
                    salt,
                    claim_assertion_type,
                ))
            }
            CAI_EMBEDDED_FILE_UUID => {
                let ef_box = assertion_box
                    .data_box_as_embedded_media_type_box(0)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let data_box = assertion_box
                    .data_box_as_embedded_file_content_box(1)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let media_type = ef_box.media_type();
                let assertion =
                    Assertion::from_data_binary(&raw_label, &media_type, data_box.data());
                let hash = Claim::calc_assertion_box_hash(label, &assertion, salt.clone(), &alg)?;
                Ok(ClaimAssertion::new(
                    assertion,
                    instance,
                    &hash,
                    &alg,
                    salt,
                    claim_assertion_type,
                ))
            }
            CAI_CBOR_ASSERTION_UUID => {
                let cbor_box = assertion_box
                    .data_box_as_cbor_box(0)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let assertion = Assertion::from_data_cbor(&raw_label, cbor_box.cbor());

                // make sure it is CBOR
                if let Err(e) = c2pa_cbor::from_slice::<c2pa_cbor::Value>(cbor_box.cbor()) {
                    log_item!(
                        label.to_owned(),
                        "invalid assertion cbor",
                        "get_assertion_from_jumbf_store"
                    )
                    .validation_status(ASSERTION_CBOR_INVALID)
                    .failure(
                        validation_log,
                        Error::AssertionDecoding(
                            AssertionDecodeError::from_assertion_and_cbor_err(&assertion, e),
                        ),
                    )?;
                }

                let hash = Claim::calc_assertion_box_hash(label, &assertion, salt.clone(), &alg)?;
                Ok(ClaimAssertion::new(
                    assertion,
                    instance,
                    &hash,
                    &alg,
                    salt,
                    claim_assertion_type,
                ))
            }
            CAI_UUID_ASSERTION_UUID => {
                let uuid_box = assertion_box
                    .data_box_as_uuid_box(0)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let uuid_str = hex::encode(uuid_box.uuid());
                let assertion = Assertion::from_data_uuid(&raw_label, &uuid_str, uuid_box.data());

                // if a redaction then make sure the data is zeros
                if uuid_str == C2PA_REDACTION_UUID {
                    let data = uuid_box.data();
                    if !is_zero(data) {
                        let assertion_absolute_uri =
                            to_assertion_uri(claim.label(), &instance_label);
                        log_item!(
                            assertion_absolute_uri,
                            "redacted assertion data must be zeros or empty",
                            "get_assertion_from_jumbf_store"
                        )
                        .validation_status(validation_status::ASSERTION_NOT_REDACTED)
                        .failure(
                            validation_log,
                            Error::OtherError(
                                "redacted assertion data must be zeros or empty".into(),
                            ),
                        )?;
                    }
                }

                let hash = Claim::calc_assertion_box_hash(label, &assertion, salt.clone(), &alg)?;
                Ok(ClaimAssertion::new(
                    assertion,
                    instance,
                    &hash,
                    &alg,
                    salt,
                    claim_assertion_type,
                ))
            }
            _ => Err(Error::JumbfCreationError),
        };

        if check_for_legacy_assertion {
            // make sure this is not pre 1.0 data
            match result {
                Ok(r) => {
                    // look for old style hashing
                    if Store::is_old_assertion(
                        &alg,
                        r.assertion().data(),
                        &assertion_hashed_uri.hash(),
                    ) {
                        Err(Error::PrereleaseError)
                    } else {
                        Ok(r)
                    }
                }
                Err(e) => Err(e),
            }
        } else {
            result
        }
    }

    pub(crate) fn to_jumbf_internal(&self, min_reserve_size: usize) -> Result<Vec<u8>> {
        // Create the CAI block.
        let mut cai_block = Cai::new();

        // Add claims and assertions in this store to the JUMBF store.
        for claim in self.claims() {
            let cai_store = Store::build_manifest_box(claim, min_reserve_size)?;

            // add the completed CAI store into the CAI block.
            cai_block.add_box(Box::new(cai_store));
        }

        // Write it to memory.
        let mut mem_box: Vec<u8> = Vec::new();
        cai_block.write_box(&mut mem_box)?;

        if mem_box.is_empty() {
            Err(Error::JumbfCreationError)
        } else {
            Ok(mem_box)
        }
    }

    fn build_manifest_box(claim: &Claim, min_reserve_size: usize) -> Result<CAIManifest> {
        // box label
        let label = claim.label();

        let manifest_type = if claim.update_manifest() {
            ManifestType::UpdateManifest
        } else if claim.is_c2md() {
            ManifestType::C2md
        } else {
            ManifestType::Manifest
        };

        let mut cai_store = CAIManifest::new(label, manifest_type, claim.compressed());

        for manifest_box in claim.get_box_order() {
            match *manifest_box {
                ASSERTIONS => {
                    let mut a_store = CAIAssertionStore::new();

                    // add assertions to CAI assertion store.
                    let cas = claim.claim_assertion_store();
                    for assertion in cas {
                        Store::add_assertion_to_jumbf_store(&mut a_store, assertion)?;
                    }

                    cai_store.add_box(Box::new(a_store)); // add the assertion store to the manifest
                }
                CLAIM => {
                    let mut cb = CAIClaimBox::new(claim.version());

                    // Add the Claim json
                    let claim_cbor_bytes = claim.data()?;
                    let c_cbor = JUMBFCBORContentBox::new(claim_cbor_bytes);
                    cb.add_claim(Box::new(c_cbor));

                    cai_store.add_box(Box::new(cb)); // add claim to manifest
                }
                SIGNATURE => {
                    // create a signature and add placeholder data to the CAI store.
                    let signed_data = match claim.signature_val().is_empty() {
                        false => claim.signature_val().clone(), // existing claims have sig values
                        true => Store::sign_claim_placeholder(claim, min_reserve_size), /* empty is the new sig to be replaced */
                    };

                    cai_store.add_box(Box::new(build_signature_box(signed_data)));
                }
                CREDENTIALS => {
                    // add vc_store if needed
                    if !claim.get_verifiable_credentials().is_empty() && claim.version() < 2 {
                        let mut vc_store = CAIVerifiableCredentialStore::new();

                        // Add assertions to CAI assertion store.
                        let vcs = claim.get_verifiable_credentials_store();
                        for (uri, assertion_data) in vcs {
                            if let AssertionData::Json(j) = assertion_data {
                                let id = Claim::vc_id(j)?;
                                let mut json_data = CAIJSONAssertionBox::new(&id);
                                json_data.add_json(j.as_bytes().to_vec());

                                if let Some(salt) = uri.salt() {
                                    json_data.set_salt(salt.clone())?;
                                }

                                vc_store.add_credential(Box::new(json_data));
                            } else {
                                return Err(Error::BadParam("VC data must be JSON".to_string()));
                            }
                        }
                        cai_store.add_box(Box::new(vc_store)); // add the CAI assertion store to manifest
                    }
                }
                DATABOXES => {
                    // Add the data boxes
                    if !claim.databoxes().is_empty() {
                        let mut databoxes = CAIDataboxStore::new();

                        for (uri, db) in claim.databoxes() {
                            let db_cbor_bytes = c2pa_cbor::to_vec(db)
                                .map_err(|err| Error::AssertionEncoding(err.to_string()))?;

                            let (link, instance) = Claim::assertion_label_from_link(&uri.url());
                            let label = Claim::label_with_instance(&link, instance);

                            let mut db_cbor = CAICBORAssertionBox::new(&label);
                            db_cbor.add_cbor(db_cbor_bytes);

                            if let Some(salt) = uri.salt() {
                                db_cbor.set_salt(salt.clone())?;
                            }

                            databoxes.add_databox(Box::new(db_cbor));
                        }

                        cai_store.add_box(Box::new(databoxes)); // add claim to manifest
                    }
                }
                _ => return Err(Error::ClaimInvalidContent),
            }
        }

        Ok(cai_store)
    }

    // calculate the hash of the manifest JUMBF box
    pub fn calc_manifest_box_hash(
        claim: &Claim,
        salt: Option<Vec<u8>>,
        alg: &str,
    ) -> Result<Vec<u8>> {
        let mut hash_bytes = Vec::with_capacity(4096);

        // build box
        let mut cai_store = Store::build_manifest_box(claim, 0)?;

        // add salt if requested
        if let Some(salt) = salt {
            cai_store.set_salt(salt)?;
        }

        // box content as Vec
        cai_store.super_box().write_box_payload(&mut hash_bytes)?;

        Ok(hash_by_alg(alg, &hash_bytes, None))
    }

    fn manifest_map<'a>(sb: &'a JUMBFSuperBox) -> Result<HashMap<String, ManifestInfo<'a>>> {
        let mut box_info: HashMap<String, ManifestInfo<'a>> = HashMap::new();
        for i in 0..sb.data_box_count() {
            let sbox = sb.data_box_as_superbox(i).ok_or(Error::JumbfBoxNotFound)?;
            let desc_box = sbox.desc_box();

            let label = desc_box.uuid();

            let mi = ManifestInfo { desc_box, sbox };

            box_info.insert(label, mi);
        }

        Ok(box_info)
    }

    // Compare two version labels
    // base_version_label - is the source label
    // desired_version_label - is the label to compare to the base
    // returns true if desired version is <= base version
    fn check_label_version(base_version_label: &str, desired_version_label: &str) -> bool {
        labels::version(desired_version_label) <= labels::version(base_version_label)
    }

    #[inline]
    pub fn from_jumbf(buffer: &[u8], validation_log: &mut StatusTracker) -> Result<Store> {
        // Legacy path: no Context available; read thread-local settings for backward compatibility.
        let max_manifest_size = get_thread_local_settings()
            .core
            .max_decompressed_manifest_size_in_mb
            .saturating_mul(1024 * 1024);
        Self::from_jumbf_impl(Store::new(), buffer, validation_log, max_manifest_size)
    }

    #[inline]
    pub fn from_jumbf_with_context(
        buffer: &[u8],
        validation_log: &mut StatusTracker,
        context: &Context,
    ) -> Result<Store> {
        let max_manifest_size = context
            .settings()
            .core
            .max_decompressed_manifest_size_in_mb
            .saturating_mul(1024 * 1024);
        Self::from_jumbf_impl(
            Store::from_context(context),
            buffer,
            validation_log,
            max_manifest_size,
        )
    }

    fn from_jumbf_impl(
        mut store: Store,
        buffer: &[u8],
        validation_log: &mut StatusTracker,
        max_manifest_size: usize,
    ) -> Result<Store> {
        if buffer.is_empty() {
            return Err(Error::JumbfNotFound);
        }

        // setup a cursor for reading the buffer...
        let mut buf_reader = Cursor::new(buffer);

        // this loads up all the boxes...
        let super_box = BoxReader::read_super_box(&mut buf_reader)?;

        // this loads up all the boxes...
        let cai_block = Cai::from(super_box);

        // check the CAI Block
        let desc_box = cai_block.desc_box();
        if desc_box.uuid() != CAI_BLOCK_UUID {
            log_item!("JUMBF", "c2pa box not found", "from_jumbf").failure_no_throw(
                validation_log,
                Error::InvalidClaim(InvalidClaimError::C2paBlockNotFound),
            );

            return Err(Error::InvalidClaim(InvalidClaimError::C2paBlockNotFound));
        }

        let num_stores = cai_block.data_box_count();
        for idx in 0..num_stores {
            let store_box = CAIManifest::from(
                cai_block
                    .data_box_as_superbox(idx)
                    .ok_or(Error::JumbfBoxNotFound)?,
                max_manifest_size,
            )?;
            let cai_store_box = store_box.super_box();
            let cai_store_desc_box = cai_store_box.desc_box();

            // ignore unknown boxes per the spec. A c2md manifest is a standard
            // manifest that consumers shall accept (C2PA spec 11.2.2), so it is
            // read the same as a c2ma manifest.
            if cai_store_desc_box.uuid() != CAI_UPDATE_MANIFEST_UUID
                && cai_store_desc_box.uuid() != CAI_MANIFEST_UUID
                && cai_store_desc_box.uuid() != CAI_MANIFEST_C2MD_UUID
            {
                continue;
            }

            // remember the order of the boxes to insure the box hashes can be regenerated
            let mut box_order: Vec<&str> = Vec::new();

            // Core boxes may appear at most once per manifest. `manifest_map` is keyed by
            // UUID (last-wins), so a duplicate would be dropped from the map yet still
            // recorded twice in `box_order`; the manifest box hash is then regenerated from
            // the single surviving box, letting byte-distinct parents collapse to the same
            // hash (the vuln-37402 ingredient parent-swap primitive).
            let mut seen_core_uuids: HashSet<String> = HashSet::new();

            // make sure there are not multiple claim boxes
            let mut claim_box_cnt = 0;
            for i in 0..cai_store_box.data_box_count() {
                let sbox = cai_store_box
                    .data_box_as_superbox(i)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let desc_box = sbox.desc_box();

                if desc_box.uuid() == CAI_CLAIM_UUID {
                    claim_box_cnt += 1;
                }

                if claim_box_cnt > 1 {
                    log_item!("JUMBF", "c2pa multiple claim boxes found", "from_jumbf")
                        .validation_status(validation_status::CLAIM_MULTIPLE)
                        .failure_no_throw(
                            validation_log,
                            Error::InvalidClaim(InvalidClaimError::C2paMultipleClaimBoxes),
                        );

                    return Err(Error::InvalidClaim(
                        InvalidClaimError::C2paMultipleClaimBoxes,
                    ));
                }

                // Reject a repeated non-claim core box before it reaches `manifest_map`
                // (duplicate claim boxes are already handled above with their own status).
                if matches!(
                    desc_box.uuid().as_str(),
                    CAI_ASSERTION_STORE_UUID
                        | CAI_SIGNATURE_UUID
                        | CAI_VERIFIABLE_CREDENTIALS_STORE_UUID
                        | CAI_DATABOXES_STORE_UUID
                ) && !seen_core_uuids.insert(desc_box.uuid())
                {
                    log_item!("JUMBF", "c2pa multiple manifest boxes found", "from_jumbf")
                        .validation_status(validation_status::CLAIM_MALFORMED)
                        .failure_no_throw(
                            validation_log,
                            Error::InvalidClaim(InvalidClaimError::C2paMultipleManifestBoxes),
                        );

                    return Err(Error::InvalidClaim(
                        InvalidClaimError::C2paMultipleManifestBoxes,
                    ));
                }

                // Derive the box order from the authoritative JUMBF type UUID,
                // not the description label. Core boxes are located by UUID in
                // `manifest_map`, so the manifest box hash must be regenerated
                // from the same UUIDs; otherwise a box whose label disagrees
                // with its UUID (e.g. a claim box relabeled `c2pa.databoxes`)
                // would be reconstructed as different content, letting distinct
                // parents collapse to the same hash.
                match desc_box.uuid().as_str() {
                    CAI_ASSERTION_STORE_UUID => box_order.push(ASSERTIONS),
                    CAI_CLAIM_UUID => box_order.push(CLAIM),
                    CAI_SIGNATURE_UUID => box_order.push(SIGNATURE),
                    CAI_VERIFIABLE_CREDENTIALS_STORE_UUID => box_order.push(CREDENTIALS),
                    CAI_DATABOXES_STORE_UUID => box_order.push(DATABOXES),
                    _ => {
                        log_item!("JUMBF", "unrecognized manifest box", "from_jumbf")
                            .validation_status(validation_status::CLAIM_MULTIPLE)
                            .failure(
                                validation_log,
                                Error::InvalidClaim(InvalidClaimError::ClaimBoxData),
                            )?;
                    }
                }
            }

            let is_update_manifest = cai_store_desc_box.uuid() == CAI_UPDATE_MANIFEST_UUID;
            let is_c2md = cai_store_desc_box.uuid() == CAI_MANIFEST_C2MD_UUID;

            // get map of boxes in this manifest
            let manifest_boxes = Store::manifest_map(cai_store_box)?;

            // retrieve the claim & validate
            let claim_superbox = manifest_boxes
                .get(CAI_CLAIM_UUID)
                .ok_or(Error::InvalidClaim(
                    InvalidClaimError::ClaimSuperboxNotFound,
                ))?
                .sbox;
            let claim_desc_box = manifest_boxes
                .get(CAI_CLAIM_UUID)
                .ok_or(Error::InvalidClaim(
                    InvalidClaimError::ClaimDescriptionBoxNotFound,
                ))?
                .desc_box;

            // check if version is supported
            let claim_box_ver = claim_desc_box.label();
            if !Self::check_label_version(&Claim::build_version_support(), &claim_box_ver) {
                return Err(Error::InvalidClaim(InvalidClaimError::ClaimVersionTooNew));
            }

            // check box contents
            if claim_desc_box.uuid() == CAI_CLAIM_UUID {
                // must be have only one claim
                if claim_superbox.data_box_count() > 1 {
                    return Err(Error::InvalidClaim(InvalidClaimError::DuplicateClaimBox {
                        label: claim_desc_box.label(),
                    }));
                }
                // better be, but just in case...

                let cbor_box = match claim_superbox.data_box_as_cbor_box(0) {
                    Some(c) => c,
                    None => {
                        // check for old claims for reporting
                        match claim_superbox.data_box_as_json_box(0) {
                            Some(_c) => {
                                log_item!("JUMBF", "error loading claim data", "from_jumbf")
                                    .failure_no_throw(validation_log, Error::PrereleaseError);

                                return Err(Error::PrereleaseError);
                            }
                            None => {
                                log_item!("JUMBF", "error loading claim data", "from_jumbf")
                                    .failure_no_throw(
                                        validation_log,
                                        Error::InvalidClaim(InvalidClaimError::ClaimBoxData),
                                    );

                                return Err(Error::InvalidClaim(InvalidClaimError::ClaimBoxData));
                            }
                        }
                    }
                };

                if cbor_box.box_uuid() != JUMBF_CBOR_UUID {
                    return Err(Error::InvalidClaim(
                        InvalidClaimError::ClaimDescriptionBoxInvalid,
                    ));
                }
            }

            // retrieve the signature
            let sig_superbox = manifest_boxes
                .get(CAI_SIGNATURE_UUID)
                .ok_or(Error::InvalidClaim(
                    InvalidClaimError::ClaimSignatureBoxNotFound,
                ))?
                .sbox;
            let sig_desc_box = manifest_boxes
                .get(CAI_SIGNATURE_UUID)
                .ok_or(Error::InvalidClaim(
                    InvalidClaimError::ClaimSignatureDescriptionBoxNotFound,
                ))?
                .desc_box;

            // check box contents
            if sig_desc_box.uuid() == CAI_SIGNATURE_UUID {
                // better be, but just in case...
                let sig_box = sig_superbox
                    .data_box_as_cbor_box(0)
                    .ok_or(Error::JumbfBoxNotFound)?;
                if sig_box.box_uuid() != JUMBF_CBOR_UUID {
                    return Err(Error::InvalidClaim(
                        InvalidClaimError::ClaimSignatureDescriptionBoxInvalid,
                    ));
                }
            }
            // save signature to be validated on load
            let sig_data = sig_superbox
                .data_box_as_cbor_box(0)
                .ok_or(Error::JumbfBoxNotFound)?;

            // Create a new Claim object from jumbf data after validations
            let cbor_box = claim_superbox
                .data_box_as_cbor_box(0)
                .ok_or(Error::JumbfBoxNotFound)?;
            let mut claim = Claim::from_data(&cai_store_desc_box.label(), cbor_box.cbor())
                .map_err(|e| {
                    log_item!(CLAIM, "CLAIM CBOR could not be decoded", "from_jumbf")
                        .validation_status(CLAIM_MALFORMED)
                        .failure_as_err(validation_log, e)
                })?;

            // the claim must have an algorithm to be able to process internal hashes
            if claim.alg_raw().is_none() {
                return Err(log_item!(
                    claim.label().to_owned(),
                    "no hashing algorithm found for claim",
                    "from_jumbf"
                )
                .validation_status(ALGORITHM_UNSUPPORTED)
                .failure_as_err(validation_log, Error::UnknownAlgorithm));
            }

            // make sure box version label match the read Claim
            if claim.version() > 1 {
                match labels::version(&claim_box_ver) {
                    v if claim.version() >= v => (),
                    _ => return Err(Error::InvalidClaim(InvalidClaimError::ClaimBoxVersion)),
                }
            }

            // set the  type of manifest
            claim.set_update_manifest(is_update_manifest);
            claim.set_is_c2md(is_c2md);

            // set order to process JUMBF boxes
            claim.set_box_order(box_order);

            // retrieve & set signature for each claim
            claim.set_signature_val(sig_data.cbor().clone()); // load the stored signature

            // set the compression status
            claim.set_compressed_manifest(store_box.compressed_store);

            // retrieve the assertion store
            let assertion_store_box = manifest_boxes
                .get(CAI_ASSERTION_STORE_UUID)
                .ok_or(Error::InvalidClaim(
                    InvalidClaimError::AssertionStoreSuperboxNotFound,
                ))?
                .sbox;

            let num_assertions = assertion_store_box.data_box_count();

            // Reject manifests that embed more assertions than the configured limit to
            // prevent unbounded memory and CPU consumption on untrusted input.
            if num_assertions > MAX_ASSERTIONS {
                return Err(Error::TooManyAssertions {
                    max: MAX_ASSERTIONS,
                });
            }

            // loop over all assertions in assertion store...
            let mut check_for_legacy_assertion = true;
            for idx in 0..num_assertions {
                let assertion_box = assertion_store_box
                    .data_box_as_superbox(idx)
                    .ok_or(Error::JumbfBoxNotFound)?;
                let assertion_desc_box = assertion_box.desc_box();

                // Add assertions to claim after validation
                let label = assertion_desc_box.label();
                match Store::get_assertion_from_jumbf_store(
                    &claim,
                    assertion_box,
                    &label,
                    check_for_legacy_assertion,
                    validation_log,
                ) {
                    Ok(assertion) => {
                        claim.put_assertion_store(assertion); // restore assertion data to claim
                        check_for_legacy_assertion = false; // only need to check once
                    }
                    Err(e) => {
                        // if this is an old manifest always return
                        if std::mem::discriminant(&e)
                            == std::mem::discriminant(&Error::PrereleaseError)
                        {
                            log_item!("JUMBF", "error loading assertion", "from_jumbf")
                                .failure_no_throw(validation_log, e);

                            return Err(Error::PrereleaseError);
                        }
                        return Err(e);
                    }
                }
            }

            // load vc_store if available
            if let Some(mi) = manifest_boxes.get(CAI_VERIFIABLE_CREDENTIALS_STORE_UUID) {
                let vc_store = mi.sbox;
                let num_vcs = vc_store.data_box_count();

                // VC stores should not be in a 2.x claim
                if claim.version() > 1 {
                    return Err(Error::InvalidClaim(InvalidClaimError::UnsupportedFeature(
                        "Verifiable Credentials Store > v1 claim".to_string(),
                    )));
                }

                for idx in 0..num_vcs {
                    let vc_box = vc_store
                        .data_box_as_superbox(idx)
                        .ok_or(Error::JumbfBoxNotFound)?;
                    let vc_json = vc_box
                        .data_box_as_json_box(0)
                        .ok_or(Error::JumbfBoxNotFound)?;
                    let vc_desc_box = vc_box.desc_box();
                    let _id = vc_desc_box.label();

                    let json_str = String::from_utf8(vc_json.json().to_vec())
                        .map_err(|_| InvalidClaimError::VerifiableCredentialStoreInvalid)?;

                    let salt = vc_desc_box.get_salt();

                    claim.put_verifiable_credential(&json_str, salt)?;
                }
            }

            // load databox store if available
            if let Some(mi) = manifest_boxes.get(CAI_DATABOXES_STORE_UUID) {
                let databox_store = mi.sbox;
                let num_databoxes = databox_store.data_box_count();

                for idx in 0..num_databoxes {
                    let db_box = databox_store
                        .data_box_as_superbox(idx)
                        .ok_or(Error::JumbfBoxNotFound)?;
                    let db_cbor = db_box
                        .data_box_as_cbor_box(0)
                        .ok_or(Error::JumbfBoxNotFound)?;
                    let db_desc_box = db_box.desc_box();
                    let label = db_desc_box.label();

                    let salt = db_desc_box.get_salt();

                    claim.put_databox(&label, db_cbor.cbor(), salt)?;
                }
            }

            // save the hash of the loaded manifest for ingredient validation
            // and the signature box for Ingredient_v3
            store.manifest_box_hash_cache.insert(
                claim.label().to_owned(),
                (
                    Store::calc_manifest_box_hash(&claim, None, claim.alg())?,
                    Claim::calc_sig_box_hash(&claim, claim.alg())?,
                ),
            );

            // add claim to store
            store.insert_restored_claim(cai_store_desc_box.label(), claim);
        }

        Ok(store)
    }

    // Get the store label from jumbf path
    pub fn manifest_label_from_path(claim_path: &str) -> String {
        if let Some(s) = jumbf::labels::manifest_label_from_uri(claim_path) {
            s
        } else {
            claim_path.to_owned()
        }
    }

    /// This function is used to get a placeholder manifest with dynamic assertion support.
    /// The placeholder is then injected into the asset before calculating hashes.
    /// Unlike [`data_hashed_placeholder`], this function supports dynamic assertions
    /// (e.g., CAWG identity assertions) by accepting a signer.
    ///
    /// # Arguments
    /// * `context` - The context to use.
    /// # Returns
    /// * The bytes of the `c2pa_manifest` placeholder.
    /// # Errors
    /// * Returns an [`Error`] if the placeholder cannot be created.
    pub fn get_placeholder(&mut self, _format: &str, context: &Context) -> Result<Vec<u8>> {
        let signer = context.signer()?;
        let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;

        // if user did not supply a hash
        if pc.hash_assertions().is_empty() {
            return Err(Error::BadParam(
                "Claim must have a hard binding assertion".to_string(),
            ));
        };

        // add dynamic assertions to the store
        let dynamic_assertions = signer.dynamic_assertions();
        let _da_uris = self.add_dynamic_assertion_placeholders(&dynamic_assertions)?;

        self.to_jumbf_internal(signer.reserve_size())
    }

    /// Signs an already hashed manifest with dynamic assertion support.
    ///
    /// # Arguments
    /// * `signer` - The signer to use.
    /// * `context` - The active context with settings.
    /// # Returns
    /// * The signed manifest bytes.
    /// # Errors
    /// * Returns an [`Error`] if the placeholder cannot be signed.
    pub fn sign_manifest(&mut self, signer: &dyn Signer, context: &Context) -> Result<Vec<u8>> {
        let settings = context.settings();
        let pc = self.provenance_claim().ok_or(Error::ClaimEncoding)?;

        // if user did not supply a hash
        if pc.hash_assertions().is_empty() {
            return Err(Error::BadParam(
                "Claim must have a valid hard binding assertion".to_string(),
            ));
        };

        // Reserve placeholder slots for any dynamic assertions exposed by the
        // signer, then write their real content in place. This must reuse the
        // same `dynamic_assertions()` result across the whole operation –
        // draining it on an earlier call is what silently dropped identity
        // assertions in issue #2055.
        let dynamic_assertions = signer.dynamic_assertions();
        if !dynamic_assertions.is_empty() {
            let missing: Vec<String> = dynamic_assertions
                .iter()
                .map(|da| da.label())
                .filter(|label| pc.assertion_hashed_uri_from_label(label).is_none())
                .collect();

            if !missing.is_empty() {
                return Err(Error::BadParam(format!(
                    "no placeholder slots were reserved for dynamic assertions [{}]; \
                     call add_dynamic_assertion_placeholders() before signing",
                    missing.join(", ")
                )));
            }

            let mut preliminary_claim = PartialClaim::default();
            for assertion in pc.assertions() {
                preliminary_claim.add_assertion(assertion);
            }

            self.write_dynamic_assertions(&dynamic_assertions, &mut preliminary_claim)?;

            let pc = self.provenance_claim().ok_or(Error::ClaimEncoding)?;
            let sig = self.sign_claim(pc, signer, signer.reserve_size(), settings)?;

            let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;
            pc.set_signature_val(sig);

            let jumbf_bytes = self.to_jumbf_internal(signer.reserve_size())?;

            if context.settings().verify.verify_after_sign {
                self.verify_store_strict(None, context)?;
            }

            return Ok(jumbf_bytes);
        }

        context.check_progress(ProgressPhase::Signing, 1, 1)?;

        let sig = self.sign_claim(pc, signer, signer.reserve_size(), settings)?;
        let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;
        pc.set_signature_val(sig);

        let jumbf_bytes = self.to_jumbf_internal(signer.reserve_size())?;

        if context.settings().verify.verify_after_sign {
            self.verify_store_strict(None, context)?;
        }

        Ok(jumbf_bytes)
    }

    /// Returns a finalized, signed manifest.  The client is required to have
    /// included the necessary box hash assertion with the pregenerated hashes.
    #[async_generic(async_signature(
        &mut self,
        signer: &dyn AsyncSigner,
        context: &Context,
    ))]
    pub fn get_box_hashed_embeddable_manifest(
        &mut self,
        signer: &dyn Signer,
        context: &Context,
    ) -> Result<Vec<u8>> {
        let pc = self.provenance_claim().ok_or(Error::ClaimEncoding)?;

        // make sure there is only one
        if pc.hash_assertions().len() != 1 {
            return Err(Error::BadParam(
                "Claim must have exactly one hash binding assertion".to_string(),
            ));
        }

        // only allow box hash assertions to be present
        if pc.box_hash_assertions().is_empty() {
            return Err(Error::BadParam("Missing box hash assertion".to_string()));
        }

        context.check_progress(ProgressPhase::Signing, 1, 1)?;

        // sign contents
        let sig = if _sync {
            self.sign_claim(pc, signer, signer.reserve_size(), context.settings())?
        } else {
            self.sign_claim_async(pc, signer, signer.reserve_size(), context.settings())
                .await?
        };

        // save the signature back to the provenance claim so it gets included in the manifest
        let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;
        pc.set_signature_val(sig);

        self.to_jumbf_internal(signer.reserve_size())
    }

    /// Inserts placeholders for dynamic assertions to be updated later.
    #[async_generic(async_signature(
        &mut self,
        dyn_assertions: &[Box<dyn AsyncDynamicAssertion>],
    ))]
    pub(crate) fn add_dynamic_assertion_placeholders(
        &mut self,
        dyn_assertions: &[Box<dyn DynamicAssertion>],
    ) -> Result<Vec<HashedUri>> {
        if dyn_assertions.is_empty() {
            return Ok(Vec::new());
        }

        // Two passes since we are accessing two fields in self.
        let mut assertions = Vec::new();
        for da in dyn_assertions.iter() {
            let reserve_size = da.reserve_size()?;
            let data1 = c2pa_cbor::ser::to_vec_packed(&vec![0; reserve_size])?;
            let cbor_delta = data1.len() - reserve_size;
            let da_data = c2pa_cbor::ser::to_vec_packed(&vec![0; reserve_size - cbor_delta])?;
            assertions.push(UserCbor::new(&da.label(), da_data));
        }

        let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;
        // add dynamic assertions (respects created_assertion_labels settings)
        assertions.iter().map(|a| pc.add_assertion(a)).collect()
    }

    /// Write the dynamic assertions to the manifest.
    ///
    /// Dynamic assertions are matched to the placeholders written by
    /// [`add_dynamic_assertion_placeholders`] by label AND instance, in the
    /// same order, so several dynamic assertions may share one label (for
    /// example two `cawg.identity` assertions from different credential
    /// holders, which become `cawg.identity` and `cawg.identity__1`).
    ///
    /// [`add_dynamic_assertion_placeholders`]: Self::add_dynamic_assertion_placeholders
    #[async_generic(async_signature(
        &mut self,
        dyn_assertions: &[Box<dyn AsyncDynamicAssertion>],
        preliminary_claim: &mut PartialClaim,
    ))]
    #[allow(unused_variables)]
    pub(super) fn write_dynamic_assertions(
        &mut self,
        dyn_assertions: &[Box<dyn DynamicAssertion>],
        preliminary_claim: &mut PartialClaim,
    ) -> Result<bool> {
        if dyn_assertions.is_empty() {
            return Ok(false);
        }

        let mut final_assertions = Vec::new();

        // Placeholders were added in this same order, so the n-th dynamic
        // assertion carrying a given label is instance n of that label.
        let mut instances: HashMap<String, usize> = HashMap::new();

        for da in dyn_assertions.iter() {
            let base_label = da.label();
            let instance = match instances.get(&base_label) {
                Some(n) => n + 1,
                None => 0,
            };
            instances.insert(base_label.clone(), instance);
            let label = Claim::label_with_instance(&base_label, instance);

            let da_size = da.reserve_size()?;
            let da_data = if _sync {
                da.content(&label, Some(da_size), preliminary_claim)?
            } else {
                da.content(&label, Some(da_size), preliminary_claim).await?
            };

            match da_data {
                DynamicAssertionContent::Cbor(data) => {
                    final_assertions
                        .push((instance, UserCbor::new(&base_label, data).to_assertion()?));
                }
                DynamicAssertionContent::Json(data) => {
                    final_assertions
                        .push((instance, User::new(&base_label, &data).to_assertion()?));
                }
                DynamicAssertionContent::Binary(format, data) => {
                    //final_assertions.push(EmbeddedData::to_binary_assertion(&EmbeddedData::new(&label, format, data))?);
                }
            }
        }

        let pc = self.provenance_claim_mut().ok_or(Error::ClaimEncoding)?;
        for (instance, assertion) in final_assertions {
            pc.replace_assertion_instance(assertion, instance)?;
        }

        // clear the provenance claim data since the contents are now different
        pc.clear_data();

        Ok(true)
    }

    /// check the input url to see if it is a supported remotes URI
    pub fn is_valid_remote_url(url: &str) -> bool {
        match url::Url::parse(url) {
            Ok(u) => u.scheme() == "http" || u.scheme() == "https",
            Err(_) => false,
        }
    }

    // get the manifest that should be used for hash binding checks
    pub(super) fn get_hash_binding_manifest(&self, claim: &Claim) -> Option<String> {
        self.get_hash_binding_manifest_impl(claim, &mut HashSet::new())
    }

    fn get_hash_binding_manifest_impl(
        &self,
        claim: &Claim,
        visited: &mut HashSet<String>,
    ) -> Option<String> {
        if !visited.insert(claim.label().to_owned()) {
            // A cyclic chain has no binding manifest.
            // None maps to a validation error in this case.
            return None;
        }

        // is this claim valid
        if !claim.update_manifest() && !claim.hash_assertions().is_empty() {
            return Some(claim.label().to_owned());
        }

        // walk the update manifests until you find an acceptable claim
        for i in claim.ingredient_assertions() {
            let ingredient = Ingredient::from_assertion(i.assertion()).ok()?;
            if ingredient.relationship == Relationship::ParentOf {
                if let Some(parent_uri) = ingredient.c2pa_manifest() {
                    let parent_label = manifest_label_from_uri(&parent_uri.url())?;
                    if let Some(parent) = self.get_claim(&parent_label) {
                        // recurse until we find
                        if parent.update_manifest() {
                            return self.get_hash_binding_manifest_impl(parent, visited);
                        } else if !parent.hash_assertions().is_empty() {
                            return Some(parent.label().to_owned());
                        }
                    }
                }
            }
        }
        None
    }

    // determine if the only changes are redacted assertions
    fn manifest_differs_by_redaction(
        c1: &Claim,
        c2: &Claim,
        redactions: &[String],
    ) -> Option<Vec<String>> {
        if let Ok(d1) = c1.data() {
            if let Ok(d2) = c2.data() {
                if d1 != d2 {
                    return None;
                }
            } else {
                return None;
            }
        } else {
            return None;
        }

        if c1.signature_val() != c2.signature_val() {
            return None;
        }

        if c1.databoxes() != c2.databoxes() {
            return None;
        }

        // get the assertion store differences
        let c1_set: HashSet<&ClaimAssertion> = c1.claim_assertion_store().iter().collect();
        let c2_set: HashSet<&ClaimAssertion> = c2.claim_assertion_store().iter().collect();

        let differences = c1_set.symmetric_difference(&c2_set).collect::<Vec<_>>();

        // are the assertion differences listed in the redaction list
        let mut redact_matches = 0;
        let mut redactions_to_remove = Vec::new();
        for difference in &differences {
            let difference_uri = to_assertion_uri(c1.label(), &difference.label());

            // was the difference in the redacted list
            if redactions
                .iter()
                .any(|redaction_uri| redaction_uri.as_str() == difference_uri.as_str())
            {
                redact_matches += 1;
                redactions_to_remove.push(difference_uri);
            }
        }

        // if all mismatches are redactions we are good
        if redact_matches == differences.len() {
            return Some(redactions_to_remove);
        }

        None
    }

    // build ingredient lists for the Claim in the specified Store
    // the referenced_ingredients map the ingredient to the claims that reference it
    // the found_redactions are any redactions found
    pub(super) fn get_claim_referenced_manifests<'a>(
        claim: &'a Claim,
        store: &'a Store,
        svi: &mut StoreValidationInfo<'a>,
        recurse: bool,
        validation_log: &mut StatusTracker,
    ) -> Result<()> {
        Self::get_claim_referenced_manifests_impl(
            claim,
            store,
            svi,
            recurse,
            validation_log,
            &mut Vec::new(),
        )
    }

    pub(super) fn get_claim_referenced_manifests_impl<'a>(
        claim: &'a Claim,
        store: &'a Store,
        svi: &mut StoreValidationInfo<'a>,
        recurse: bool,
        validation_log: &mut StatusTracker,
        claim_label_path: &mut Vec<&'a str>,
    ) -> Result<()> {
        // `claim_label_path` is the chain of claims currently being walked
        // recursively: each entry pushes on entry (line below) and pops on
        // return (end of function), so its length is the current recursion
        // depth — not the total number of ingredients seen. A claim with a
        // million sibling ingredients still recurses at depth 1 per sibling.
        if claim_label_path.len() >= MAX_INGREDIENT_DEPTH {
            return Err(Error::InvalidAsset(format!(
                "ingredient chain depth ({}) exceeds maximum ({})",
                claim_label_path.len(),
                MAX_INGREDIENT_DEPTH
            )));
        }

        let claim_label = claim.label();

        if svi.manifest_map.contains_key(claim_label) {
            return Ok(());
        }

        claim_label_path.push(claim_label);

        // add in current redactions
        if let Some(c_redactions) = claim.redactions() {
            svi.redactions.extend(c_redactions.iter().cloned());
        }

        // save the addressible claims for quicker lookup
        svi.manifest_map.insert(claim_label.to_owned(), claim);

        for i in claim.ingredient_assertions() {
            let ingredient_assertion = Ingredient::from_assertion(i.assertion())?;

            // get correct hashed URI
            let c2pa_manifest = match ingredient_assertion.c2pa_manifest() {
                Some(m) => m, // > v2 ingredient assertion
                None => continue,
            };

            // is this an ingredient
            let ingredient_label = Store::manifest_label_from_path(&c2pa_manifest.url());

            if let Some(ingredient) = store.get_claim(&ingredient_label) {
                if claim_label_path.contains(&ingredient.label()) {
                    return Err(log_item!(
                        jumbf::labels::to_assertion_uri(claim_label, &i.label()),
                        "ingredient cannot be cyclic",
                        "ingredient_checks"
                    )
                    .validation_status(validation_status::ASSERTION_INGREDIENT_MALFORMED)
                    .failure_as_err(
                        validation_log,
                        Error::CyclicIngredients {
                            claim_label_path: claim_label_path
                                .iter()
                                .map(|&label| label.to_owned())
                                .collect(),
                        },
                    ));
                }

                // build mapping of ingredients and those claims that reference it
                svi.ingredient_references
                    .entry(ingredient_label.clone())
                    .or_insert(HashSet::from_iter(vec![claim_label.to_owned()]))
                    .insert(claim_label.to_owned());

                // recurse nested ingredients
                if recurse {
                    Store::get_claim_referenced_manifests_impl(
                        ingredient,
                        store,
                        svi,
                        recurse,
                        validation_log,
                        claim_label_path,
                    )?;
                }
            } else {
                log_item!(
                    ingredient_label.clone(),
                    "ingredient manifest missing",
                    "get_claim_referenced_manifests"
                )
                .validation_status(validation_status::INGREDIENT_MANIFEST_MISSING)
                .failure(
                    validation_log,
                    Error::ClaimMissing {
                        label: ingredient_label,
                    },
                )?;
            }
        }

        claim_label_path.pop();

        Ok(())
    }

    /// Load Store from memory and add its content as a claim ingredient
    /// claim: claim to add an ingredient
    /// provenance_label: label of the provenance claim used as key into ingredient map
    /// data: jumbf data block
    /// returns new Store with ingredients loaded, claim is modified to include resolved
    /// ingredients conflicts
    pub fn load_ingredient_to_claim(
        claim: &mut Claim,
        data: &[u8],
        redactions: Option<Vec<String>>,
        context: &Context,
    ) -> Result<Store> {
        // constants for ingredient conflict reasons
        const CONFLICTING_MANIFEST: usize = 1; // Conflicts with another C2PA Manifest

        let mut to_both = Vec::new();
        let mut to_remove_from_incoming = Vec::new();

        let mut report = StatusTracker::with_error_behavior(ErrorBehavior::StopOnFirstError);
        let i_store = Store::from_jumbf_with_context(data, &mut report, context)?;

        let empty_store = Store::default();

        // make sure the claims stores are compatible
        let ingredient_pc = i_store.provenance_claim().ok_or(Error::OtherError(
            "ingredient missing provenace claim".into(),
        ))?;
        if claim.version() < ingredient_pc.version() {
            return Err(Error::OtherError("ingredient version too new".into()));
        }

        // get list of referenced manifests and redactions from ingredient provenance claim
        let mut validation_log = StatusTracker::default();
        let mut svi = StoreValidationInfo::default();
        Store::get_claim_referenced_manifests(
            ingredient_pc,
            &i_store,
            &mut svi,
            true,
            &mut validation_log,
        )?;

        // resolve conflicts
        // for 2.x perform ingredients conflict handling by making new label if needed
        let skip_resolution = context
            .settings()
            .verify
            .skip_ingredient_conflict_resolution;

        if claim.version() > 1 && !skip_resolution {
            // if the hashes match then the values are OK to add so remove form conflict list
            // matching manifests are automatically deduped in a later step
            let potential_conflicts: Vec<_> = i_store
                .claims()
                .iter()
                .filter_map(|i_claim| {
                    for c in claim.claim_ingredients() {
                        if c.label() == i_claim.label() {
                            let i_ingredient_hashes = i_store.get_manifest_box_hashes(i_claim);
                            let current_claim_hashes = empty_store.get_manifest_box_hashes(c);

                            // if they match there is no conflict
                            if !vec_compare(
                                &current_claim_hashes.manifest_box_hash,
                                &i_ingredient_hashes.manifest_box_hash,
                            ) {
                                return Some(c.label().to_owned());
                            }
                        }
                    }

                    None
                })
                .collect();

            if !potential_conflicts.is_empty() {
                // get info about conflicting Claim from current claim
                let mut claim_redactions: Vec<String> = redactions.clone().unwrap_or_default();
                for c in claim.claim_ingredients() {
                    if let Some(r) = c.redactions() {
                        claim_redactions.extend(r.iter().cloned());
                    }
                }

                let combined_redactions = HashSet::<_>::from_iter(
                    vec![claim_redactions.clone(), svi.redactions.clone()]
                        .into_iter()
                        .flatten(),
                )
                .into_iter()
                .collect::<Vec<String>>();

                // do any of the conflicting manifests contain redactions
                for conflict_label in potential_conflicts {
                    // Step 1: was the conflict because of a redaction from the either the current
                    // claim or the incoming store

                    let conflict = i_store
                        .get_claim(&conflict_label)
                        .ok_or(Error::IngredientNotFound)?;

                    // can only resolve conflict if the changes were redaction differences
                    if let Some(curr_claim_ingredient_conflict) = claim
                        .claim_ingredients()
                        .iter()
                        .find(|c| c.label() == conflict_label)
                    {
                        if let Some(mut differences) = Store::manifest_differs_by_redaction(
                            curr_claim_ingredient_conflict,
                            conflict,
                            &combined_redactions,
                        ) {
                            if !claim_redactions.is_empty() && svi.redactions.is_empty() {
                                // if redactions were only in the claim we can skip bringing the ingredient
                                to_remove_from_incoming.push(conflict_label.clone());
                            } else if claim_redactions.is_empty() && !svi.redactions.is_empty() {
                                // if redactions were only from the incoming ingredient replace claim
                                // noting to do here since the incoming claim will just overwrite the current claim
                                continue;
                            } else {
                                to_both.append(&mut differences);
                            }
                        } else {
                            // First conflict for this label starts at version 1
                            let new_version = claim
                                .claim_ingredient_store()
                                .keys()
                                .filter_map(|label| manifest_label_to_parts(label)?.version)
                                .max()
                                .map_or(1, |last_conflict_version| last_conflict_version + 1);

                            // make new ingredient label
                            let mut new_mp = manifest_label_to_parts(&conflict_label)
                                .ok_or(Error::OtherError("ingredient label malformed".into()))?;
                            new_mp.version = Some(new_version);
                            new_mp.reason = Some(CONFLICTING_MANIFEST);
                            let new_label = new_mp.to_string();

                            // update ingredient manifest label to new label
                            let mut fixup_claim = i_store
                                .get_claim(conflict.label())
                                .ok_or(Error::IngredientNotFound)?
                                .clone();
                            fixup_claim.set_conflict_label(new_label.clone());

                            // add relabeled manifest to store as new ingredient
                            claim.add_ingredient_data(
                                vec![fixup_claim],
                                None,
                                &svi.ingredient_references,
                            )?;
                        }
                    }
                }
            }
        }

        // make necessary changes to the incoming store
        let mut i_store_mut = Store::from_jumbf_with_context(data, &mut report, context)?;
        let mut final_redactions = HashSet::new();
        if let Some(redactions) = redactions {
            for r in redactions {
                final_redactions.insert(r);
            }
        }

        // For each redaction that targets an ingredient assertion, remove the corresponding
        // entry from ingredient_references. If no other claim still references that ingredient
        // claim, drop it from the incoming store entirely.
        for redaction_uri in &final_redactions {
            let assertion_label = match assertion_label_from_uri(redaction_uri) {
                Some(l) => l,
                None => continue,
            };

            // Only act on ingredient assertions.
            if !assertion_label.starts_with(labels::INGREDIENT) {
                continue;
            }

            // The redaction URI encodes which claim owns the assertion.
            let claim_label = match manifest_label_from_uri(redaction_uri) {
                Some(l) => l,
                None => continue,
            };

            // Find the owning claim and then the specific assertion within it.
            let Some(owning_claim) = i_store.get_claim(&claim_label) else {
                continue;
            };

            let Some(ia) = owning_claim
                .ingredient_assertions()
                .into_iter()
                .find(|a| a.label() == assertion_label)
            else {
                continue;
            };

            // Recover the referenced manifest URL from active_manifest or c2pa_manifest.
            let Ok(ingredient_assertion) = Ingredient::from_assertion(ia.assertion()) else {
                continue;
            };

            let Some(manifest_ref) = ingredient_assertion.c2pa_manifest() else {
                continue;
            };

            let ingredient_label = Store::manifest_label_from_path(&manifest_ref.url());

            let now_unreferenced =
                if let Some(refs) = svi.ingredient_references.get_mut(&ingredient_label) {
                    refs.remove(&claim_label);
                    refs.is_empty()
                } else {
                    false
                };

            if now_unreferenced {
                svi.ingredient_references.remove(&ingredient_label);
                to_remove_from_incoming.push(ingredient_label);
            }
        }

        // remove the claims from the incoming store as to not overwrite the current claim
        for label in to_remove_from_incoming {
            i_store_mut.remove_claim(&label);
        }

        // if there are redactions in both apply the current redaction to incoming claim
        if !to_both.is_empty() {
            for r in to_both.iter() {
                final_redactions.insert(r.to_owned());
            }

            // copy the redactions differences from current to incoming claim
            final_redactions.retain(|f| !svi.redactions.contains(f));
        }

        let claims_to_add: Vec<Claim> = i_store_mut.claims().into_iter().cloned().collect();
        claim.add_ingredient_data(
            claims_to_add,
            Some(final_redactions.into_iter().collect()),
            &svi.ingredient_references,
        )?;
        Ok(i_store)
    }
}

impl std::fmt::Display for Store {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let report = &ManifestStoreReport::from_store(self).unwrap_or_default();
        f.write_str(&format!("{}", report))
    }
}