didwebvh-rs 0.5.2

Implementation of the did:webvh method in Rust
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
/*!
*   Webvh utilizes Log Entries for each version change of the DID Document.
*/
use crate::{
    DIDWebVHError, Version,
    log_entry::{spec_1_0::LogEntry1_0, spec_1_0_pre::LogEntry1_0Pre},
    parameters::Parameters,
    witness::Witnesses,
};
use affinidi_data_integrity::{DataIntegrityProof, VerifyOptions};
use base58::ToBase58;
use chrono::{DateTime, FixedOffset};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use serde_json_canonicalizer::to_string;
use sha2::{Digest, Sha256};
use std::{fs::OpenOptions, io::Write};
use tracing::debug;

pub mod read;
pub mod spec_1_0;
pub mod spec_1_0_pre;

/// Encodes a SHA-256 digest as a multihash byte array.
/// Multihash format: [hash_function_code, digest_length, ...digest_bytes]
/// SHA-256 code = 0x12, digest length = 0x20 (32 bytes)
pub(crate) fn encode_sha256_multihash(digest: &[u8]) -> Vec<u8> {
    let mut buf = Vec::with_capacity(2 + digest.len());
    buf.push(0x12); // SHA-256 hash function code
    buf.push(0x20); // 32 bytes digest length
    buf.extend_from_slice(digest);
    buf
}

/// Resolved Document MetaData
/// Returned as resolved Document MetaData on a successful resolve
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetaData {
    /// The `<version_number>-<hash>` identifier for this log entry.
    pub version_id: String,
    /// Integer version number parsed from `version_id` (e.g. `2` for
    /// `"2-Qm..."`). Exposed as a sibling of `version_id` for consumers
    /// that want the integer without parsing the string.
    pub version_number: u32,
    /// RFC 3339 timestamp when this version was created.
    pub version_time: String,
    /// RFC 3339 timestamp when the DID was first created.
    pub created: String,
    /// RFC 3339 timestamp of the most recent update.
    pub updated: String,
    /// Self-Certifying Identifier (SCID) for the DID.
    pub scid: String,
    /// Whether the DID is portable (can change its web address).
    pub portable: bool,
    /// Whether the DID has been deactivated.
    pub deactivated: bool,
    /// Active witness configuration, if any.
    pub witness: Option<Witnesses>,
    /// Watcher endpoints configured for this DID.
    pub watchers: Option<Vec<String>>,
}

/// Extracts raw public key bytes from a data integrity proof.
pub trait PublicKey {
    /// Decode the verification method into raw public key bytes.
    fn get_public_key_bytes(&self) -> Result<Vec<u8>, DIDWebVHError>;
}

/// Enforces the didwebvh 1.0 shape constraints on a witness proof before
/// cryptographic verification: cryptosuite must be `eddsa-jcs-2022` (unless
/// the caller widened the allowed set via [`WitnessVerifyOptions`]), and
/// `proofPurpose` must be `assertionMethod`. Returns an error mentioning
/// the exact violation — the spec is unambiguous here, so silent acceptance
/// would hide real interop bugs.
///
/// [`WitnessVerifyOptions`]: crate::witness::WitnessVerifyOptions
pub(crate) fn enforce_witness_proof_shape(
    proof: &DataIntegrityProof,
    options: &crate::witness::WitnessVerifyOptions,
) -> Result<(), DIDWebVHError> {
    if !options.suite_is_allowed(proof.cryptosuite) {
        return Err(DIDWebVHError::WitnessProofError(format!(
            "witness proof uses cryptosuite {:?}, but the didwebvh 1.0 spec \
             requires eddsa-jcs-2022 (add to WitnessVerifyOptions::extra_allowed_suites \
             to accept non-spec suites explicitly)",
            proof.cryptosuite
        )));
    }
    if proof.proof_purpose != "assertionMethod" {
        return Err(DIDWebVHError::WitnessProofError(format!(
            "witness proof has proofPurpose '{}', but the didwebvh 1.0 spec \
             requires 'assertionMethod'",
            proof.proof_purpose
        )));
    }
    Ok(())
}

impl PublicKey for DataIntegrityProof {
    fn get_public_key_bytes(&self) -> Result<Vec<u8>, DIDWebVHError> {
        // Delegate to the upstream resolver: it knows every multicodec
        // registered for public keys (Ed25519, secp256k1, P-256/384/521,
        // and — with feature gates — the ML-DSA / SLH-DSA variants) and
        // validates the decoded length. Centralising the logic upstream
        // means new key types added in affinidi-data-integrity flow
        // through here without a didwebvh-rs patch.
        Ok(
            affinidi_data_integrity::did_vm::resolve_did_key(&self.verification_method)
                .map_err(|e| {
                    DIDWebVHError::InvalidMethodIdentifier(format!(
                        "could not resolve did:key verificationMethod: {e}"
                    ))
                })?
                .public_key_bytes,
        )
    }
}

/// Each version of the DID gets a new log entry
/// [Log Entries](https://identity.foundation/didwebvh/v1.0/#the-did-log-file)
#[non_exhaustive]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum LogEntry {
    /// Official v1.0 specification
    Spec1_0(LogEntry1_0),

    /// Interim 1.0 spec where nulls were used instead of empty arrays and objects
    Spec1_0Pre(LogEntry1_0Pre),
}

/// Common accessors shared by all log entry versions.
pub trait LogEntryMethods {
    /// LogEntry Parameters versionTime
    fn get_version_time_string(&self) -> String;

    /// LogEntry Parameters versionTime
    fn get_version_time(&self) -> DateTime<FixedOffset>;

    /// Returns the versionId for this log entry.
    fn get_version_id(&self) -> &str;

    /// Set the versionId to an updated value.
    fn set_version_id(&mut self, version_id: &str);

    /// Get Parameters
    fn get_parameters(&self) -> Parameters;

    /// Add a proof for this log entry.
    fn add_proof(&mut self, proof: DataIntegrityProof);

    /// Get proofs for this log entry.
    fn get_proofs(&self) -> &[DataIntegrityProof];

    /// Resets all proofs for this LogEntry
    fn clear_proofs(&mut self);

    /// Returns the SCID if present in this log entry's parameters.
    fn get_scid(&self) -> Option<&str>;

    /// Get the raw DID Document state
    /// Does NOT include implied services
    fn get_state(&self) -> &Value;

    /// Returns a full DID Document including implied services
    /// (`#files` / `#whois`).
    ///
    /// This builds a fresh `Value` by cloning `state` and appending any
    /// missing implicit services — the LogEntry itself is **not** mutated.
    /// The returned document is for **resolution / display only**.
    ///
    /// # âš  DO NOT feed this back into [`create_log_entry`] or [`update`]
    ///
    /// The hash chain (`versionId`, SCID, `eddsa-jcs-2022` proofs) is
    /// computed over the LogEntry's stored `state`, which by spec excludes
    /// the implicit services. Passing the augmented document from
    /// `get_did_document()` as the new `state` would bake `#files` and
    /// `#whois` into the canonical bytes, breaking interop with every other
    /// didwebvh implementation. If you need the document for an update, use
    /// [`get_state`](Self::get_state) instead.
    ///
    /// [`create_log_entry`]: crate::DIDWebVHState::create_log_entry
    /// [`update`]: crate::update::update_did
    fn get_did_document(&self) -> Result<Value, DIDWebVHError>;
}

/// Where-ever we need to create a LogEntry across versions
pub(crate) trait LogEntryCreate {
    fn create(
        version_id: String,
        version_time: DateTime<FixedOffset>,
        parameters: Parameters,
        state: Value,
    ) -> Result<LogEntry, DIDWebVHError>;
}

/// Shared helper: serialize versionTime with seconds-only precision
pub(crate) fn format_version_time<S>(
    date: &DateTime<FixedOffset>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&date.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
}

/// Shared helper: split a versionId into (number, hash)
pub fn parse_version_id_fields(version_id: &str) -> Result<(u32, String), DIDWebVHError> {
    let Some((id, hash)) = version_id.split_once('-') else {
        return Err(DIDWebVHError::ValidationError(format!(
            "versionID ({version_id}) doesn't match format <int>-<hash>",
        )));
    };
    let id = id.parse::<u32>().map_err(|e| {
        DIDWebVHError::ValidationError(format!("Failed to parse version ID ({id}) as u32: {e}",))
    })?;
    Ok((id, hash.to_string()))
}

/// Implements the common inherent methods and `LogEntryMethods` trait for a log entry struct.
///
/// The struct must have fields: `version_id`, `version_time`, `parameters`, `state`, `proof`.
/// The parameters type must implement `Into<Parameters>` and `Clone`.
macro_rules! impl_log_entry_common {
    ($type:ty) => {
        impl $type {
            /// Calculates a Log Entry hash
            pub fn generate_log_entry_hash(&self) -> Result<String, DIDWebVHError> {
                let jcs = serde_json_canonicalizer::to_string(self).map_err(|e| {
                    DIDWebVHError::SCIDError(format!(
                        "Couldn't generate JCS from LogEntry. Reason: {e}",
                    ))
                })?;
                tracing::debug!("JCS for LogEntry hash: {}", jcs);

                let digest = <sha2::Sha256 as sha2::Digest>::digest(jcs.as_bytes());
                let multihash_bytes = crate::log_entry::encode_sha256_multihash(digest.as_slice());
                Ok(base58::ToBase58::to_base58(multihash_bytes.as_slice()))
            }

            /// Verifies a witness data integrity proof against this log entry's versionId.
            pub fn validate_witness_proof(
                &self,
                witness_proof: &affinidi_data_integrity::DataIntegrityProof,
                options: &crate::witness::WitnessVerifyOptions,
            ) -> Result<bool, DIDWebVHError> {
                use crate::log_entry::PublicKey;
                crate::log_entry::enforce_witness_proof_shape(witness_proof, options)?;
                witness_proof
                    .verify_with_public_key(
                        &serde_json::json!({"versionId": &self.version_id}),
                        witness_proof.get_public_key_bytes()?.as_slice(),
                        affinidi_data_integrity::VerifyOptions::new(),
                    )
                    .map_err(|e| {
                        DIDWebVHError::LogEntryError(format!(
                            "Data Integrity Proof verification failed: {e}"
                        ))
                    })?;
                Ok(true)
            }

            /// Splits the version number and the version hash for a DID versionId
            pub fn get_version_id_fields(&self) -> Result<(u32, String), DIDWebVHError> {
                crate::log_entry::parse_version_id_fields(&self.version_id)
            }

            /// Splits the version number and the version hash for a DID versionId
            pub fn parse_version_id_fields(
                version_id: &str,
            ) -> Result<(u32, String), DIDWebVHError> {
                crate::log_entry::parse_version_id_fields(version_id)
            }
        }

        impl crate::log_entry::LogEntryMethods for $type {
            fn get_version_time_string(&self) -> String {
                self.version_time
                    .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
            }

            fn get_version_time(&self) -> chrono::DateTime<chrono::FixedOffset> {
                self.version_time
            }

            fn get_version_id(&self) -> &str {
                &self.version_id
            }

            fn set_version_id(&mut self, version_id: &str) {
                self.version_id = version_id.to_string();
            }

            fn get_parameters(&self) -> crate::parameters::Parameters {
                self.parameters.clone().into()
            }

            fn add_proof(&mut self, proof: affinidi_data_integrity::DataIntegrityProof) {
                self.proof.push(proof);
            }

            fn get_proofs(&self) -> &[affinidi_data_integrity::DataIntegrityProof] {
                &self.proof
            }

            fn clear_proofs(&mut self) {
                self.proof.clear();
            }

            fn get_scid(&self) -> Option<&str> {
                self.parameters.scid.as_deref().map(String::as_str)
            }

            fn get_state(&self) -> &serde_json::Value {
                &self.state
            }

            fn get_did_document(&self) -> Result<serde_json::Value, DIDWebVHError> {
                let services = self.state.get("service");
                let mut new_state = self.state.clone();
                if let Some(id) = self.state.get("id")
                    && let Some(id) = id.as_str()
                {
                    crate::resolve::implicit::update_implicit_services(
                        services, &mut new_state, id,
                    )?;
                    Ok(new_state)
                } else {
                    Err(DIDWebVHError::ValidationError(
                        "DID Document is missing 'id' field or it's not a string".to_string(),
                    ))
                }
            }
        }
    };
}

pub(crate) use impl_log_entry_common;

impl LogEntry {
    /// Reading in a LogEntry and converting it requires custom logic.
    /// `deserialize_string` handles detecting the version and deserializing the LogEntry correctly
    /// Attributes:
    /// - input: The input string to deserialize
    /// - version: If you want to override the default latest version, specify the previous
    ///   LogEntry version here
    pub fn deserialize_string(
        input: &str,
        version: Option<Version>,
    ) -> Result<LogEntry, DIDWebVHError> {
        // Step 1: Parse the String to generic JSON Values
        let values: Value = serde_json::from_str(input).map_err(|e| {
            DIDWebVHError::LogEntryError(format!("Couldn't deserialize LogEntry. Reason: {e}"))
        })?;

        // Step 2: Detect method version
        let version = if let Some(parameters) = values.get("parameters") {
            if let Some(method) = parameters.get("method") {
                if let Some(method) = method.as_str() {
                    Version::try_from(method).unwrap_or(version.unwrap_or_default())
                } else {
                    version.unwrap_or_default()
                }
            } else {
                version.unwrap_or_default()
            }
        } else {
            version.unwrap_or_default()
        };

        // Step 3: Deserialize using the LogEntry method version

        match version {
            Version::V1_0 => {
                // There is a pre-ratified difference in the v1.0 spec where nulls were used
                // instead of empty arrays and objects
                let Some(parameters) = values.get("parameters") else {
                    return Err(DIDWebVHError::LogEntryError(
                        "No parameters exist in the LogEntry!".to_string(),
                    ));
                };

                // Check if there are JSON nulls in the parameters
                let mut pre_version = false;
                if let Some(v) = parameters.get("updateKeys")
                    && v.is_null()
                {
                    pre_version = true;
                }
                if let Some(v) = parameters.get("nextKeyHashes")
                    && v.is_null()
                {
                    pre_version = true;
                }
                if let Some(v) = parameters.get("witness")
                    && v.is_null()
                {
                    pre_version = true;
                }
                if let Some(v) = parameters.get("watchers")
                    && v.is_null()
                {
                    pre_version = true;
                }
                if let Some(v) = parameters.get("ttl")
                    && v.is_null()
                {
                    pre_version = true;
                }

                if pre_version {
                    Ok(LogEntry::Spec1_0Pre(
                        serde_json::from_value::<LogEntry1_0Pre>(values).map_err(|e| {
                            DIDWebVHError::LogEntryError(format!("Failed to parse LogEntry: {e}"))
                        })?,
                    ))
                } else {
                    Ok(LogEntry::Spec1_0(
                        serde_json::from_value::<LogEntry1_0>(values).map_err(|e| {
                            DIDWebVHError::LogEntryError(format!("Failed to parse LogEntry: {e}"))
                        })?,
                    ))
                }
            }
            _ => Err(DIDWebVHError::LogEntryError(format!(
                "Version ({version}) is not supported!"
            ))),
        }
    }

    /// Get the WebVH Specification version for this LogEntry
    pub fn get_webvh_version(&self) -> Version {
        match self {
            LogEntry::Spec1_0(_) => Version::V1_0,
            LogEntry::Spec1_0Pre(_) => Version::V1_0Pre,
        }
    }

    /// Converts a string into the correct version when version is known
    pub fn from_string_to_known_version(
        input: &str,
        version: Version,
    ) -> Result<LogEntry, DIDWebVHError> {
        match version {
            Version::V1_0 => serde_json::from_str::<LogEntry1_0>(input)
                .map(LogEntry::Spec1_0)
                .map_err(|e| {
                    DIDWebVHError::LogEntryError(format!("Failed to parse LogEntry: {e}"))
                }),
            Version::V1_0Pre => serde_json::from_str::<LogEntry1_0Pre>(input)
                .map(LogEntry::Spec1_0Pre)
                .map_err(|e| {
                    DIDWebVHError::LogEntryError(format!("Failed to parse LogEntry: {e}"))
                }),
        }
    }

    /// Append a valid LogEntry to a file
    pub fn save_to_file(&self, file_path: &str) -> Result<(), DIDWebVHError> {
        let append = if self.get_version_id_fields()?.0 == 1 {
            false // Don't append to the file if this is the first version
        } else {
            true // Append to the file for all subsequent versions
        };

        let mut file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(!append)
            .append(append)
            .open(file_path)
            .map_err(|e| {
                DIDWebVHError::LogEntryError(format!("Couldn't open file {file_path}: {e}"))
            })?;

        file.write_all(
            serde_json::to_string(self)
                .map_err(|e| {
                    DIDWebVHError::LogEntryError(format!(
                        "Couldn't serialize LogEntry to JSON. Reason: {e}",
                    ))
                })?
                .as_bytes(),
        )
        .map_err(|e| {
            DIDWebVHError::LogEntryError(format!(
                "Couldn't append LogEntry to file({file_path}). Reason: {e}",
            ))
        })?;
        file.write_all("\n".as_bytes()).map_err(|e| {
            DIDWebVHError::LogEntryError(format!(
                "Couldn't append LogEntry to file({file_path}). Reason: {e}",
            ))
        })?;

        Ok(())
    }

    /// Generates a SCID from a preliminary LogEntry
    /// This only needs to be called once when the DID is first created.
    pub(crate) fn generate_first_scid(&self) -> Result<String, DIDWebVHError> {
        self.generate_log_entry_hash().map_err(|e| {
            DIDWebVHError::SCIDError(format!(
                "Couldn't generate SCID from preliminary LogEntry. Reason: {e}",
            ))
        })
    }

    /// Calculates a Log Entry hash
    pub fn generate_log_entry_hash(&self) -> Result<String, DIDWebVHError> {
        let jcs = to_string(self).map_err(|e| {
            DIDWebVHError::SCIDError(format!("Couldn't generate JCS from LogEntry. Reason: {e}",))
        })?;
        debug!("JCS for LogEntry hash: {}", jcs);

        let digest = Sha256::digest(jcs.as_bytes());
        let multihash_bytes = encode_sha256_multihash(digest.as_slice());
        Ok(multihash_bytes.to_base58())
    }

    /// Validates a witness proof against the log entry
    pub fn validate_witness_proof(
        &self,
        witness_proof: &DataIntegrityProof,
        options: &crate::witness::WitnessVerifyOptions,
    ) -> Result<bool, DIDWebVHError> {
        enforce_witness_proof_shape(witness_proof, options)?;
        // Verify the Data Integrity Proof against the Signing Document
        witness_proof
            .verify_with_public_key(
                &json!({"versionId": self.get_version_id()}),
                witness_proof.get_public_key_bytes()?.as_slice(),
                VerifyOptions::new(),
            )
            .map_err(|e| {
                DIDWebVHError::LogEntryError(format!(
                    "Data Integrity Proof verification failed: {e}"
                ))
            })?;

        Ok(true)
    }

    /// Splits the version number and the version hash for a DID versionId
    pub fn get_version_id_fields(&self) -> Result<(u32, String), DIDWebVHError> {
        match self {
            LogEntry::Spec1_0(log_entry) => parse_version_id_fields(&log_entry.version_id),
            LogEntry::Spec1_0Pre(log_entry) => parse_version_id_fields(&log_entry.version_id),
        }
    }

    /// Splits the version number and the version hash for a DID versionId
    pub fn parse_version_id_fields(version_id: &str) -> Result<(u32, String), DIDWebVHError> {
        parse_version_id_fields(version_id)
    }

    /// Create a new LogEntry depending on the WebVH Version
    pub(crate) fn create(
        version_id: String,
        version_time: DateTime<FixedOffset>,
        parameters: Parameters,
        state: Value,
        webvh_version: Version,
    ) -> Result<LogEntry, DIDWebVHError> {
        match webvh_version {
            Version::V1_0 => LogEntry1_0::create(version_id, version_time, parameters, state),
            Version::V1_0Pre => Err(DIDWebVHError::LogEntryError(
                "WebVH Version must be 1.0 or higher".to_string(),
            )),
        }
    }
}

impl LogEntryMethods for LogEntry {
    fn get_version_time_string(&self) -> String {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_version_time_string(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_version_time_string(),
        }
    }

    fn get_version_id(&self) -> &str {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_version_id(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_version_id(),
        }
    }

    fn set_version_id(&mut self, version_id: &str) {
        match self {
            LogEntry::Spec1_0(log_entry) => {
                log_entry.set_version_id(version_id);
            }
            LogEntry::Spec1_0Pre(log_entry) => {
                log_entry.set_version_id(version_id);
            }
        }
    }

    fn get_parameters(&self) -> Parameters {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_parameters(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_parameters(),
        }
    }

    fn add_proof(&mut self, proof: DataIntegrityProof) {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.add_proof(proof),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.add_proof(proof),
        }
    }

    fn get_proofs(&self) -> &[DataIntegrityProof] {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_proofs(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_proofs(),
        }
    }

    fn clear_proofs(&mut self) {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.clear_proofs(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.clear_proofs(),
        }
    }

    fn get_scid(&self) -> Option<&str> {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_scid(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_scid(),
        }
    }

    fn get_version_time(&self) -> DateTime<FixedOffset> {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_version_time(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_version_time(),
        }
    }

    fn get_state(&self) -> &Value {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_state(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_state(),
        }
    }

    fn get_did_document(&self) -> Result<Value, DIDWebVHError> {
        match self {
            LogEntry::Spec1_0(log_entry) => log_entry.get_did_document(),
            LogEntry::Spec1_0Pre(log_entry) => log_entry.get_did_document(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Version, parameters::spec_1_0::Parameters1_0};
    use affinidi_data_integrity::{DataIntegrityProof, crypto_suites::CryptoSuite};
    use chrono::Utc;
    use serde_json::json;

    // ===== MetaData tests =====

    /// `MetaData::version_number` serialises as `versionNumber` alongside
    /// `versionId`. Required for TS-interop parity with didwebvh-ts resolver
    /// output.
    #[test]
    fn metadata_serialises_version_number_as_camel_case_integer() {
        let meta = MetaData {
            version_id: "42-QmExample".to_string(),
            version_number: 42,
            version_time: "2000-01-01T00:00:00Z".to_string(),
            created: "2000-01-01T00:00:00Z".to_string(),
            updated: "2000-01-01T00:00:00Z".to_string(),
            scid: "QmExample".to_string(),
            portable: false,
            deactivated: false,
            witness: None,
            watchers: None,
        };
        let v = serde_json::to_value(&meta).unwrap();
        assert_eq!(v.get("versionNumber"), Some(&serde_json::json!(42)));
        assert_eq!(v.get("versionId"), Some(&serde_json::json!("42-QmExample")));
        let round_tripped: MetaData = serde_json::from_value(v).unwrap();
        assert_eq!(round_tripped.version_number, 42);
    }

    // ===== PublicKey trait tests =====

    /// Tests that extracting a public key from a proof whose verification method
    /// does not start with "did:key:" returns an error.
    /// Expected: Returns an error mentioning "did:key:".
    /// This matters because WebVH log entry proofs must use did:key verification
    /// methods; rejecting other DID methods prevents invalid key extraction.
    #[test]
    fn test_public_key_not_did_key_error() {
        let proof = DataIntegrityProof {
            type_: "test".to_string(),
            created: None,
            context: None,
            cryptosuite: CryptoSuite::EddsaJcs2022,
            proof_purpose: "test".to_string(),
            proof_value: None,
            verification_method: "did:web:example.com#key-1".to_string(),
        };
        let err = proof.get_public_key_bytes().unwrap_err();
        assert!(err.to_string().contains("did:key:"));
    }

    /// Tests that a did:key verification method missing the fragment separator (#)
    /// returns an "Invalid verification method" error.
    /// Expected: Returns an error indicating the verification method format is invalid.
    /// This matters because the public key is extracted from the fragment portion
    /// after the '#'; without it, key extraction cannot proceed safely.
    #[test]
    fn test_public_key_missing_hash_error() {
        let proof = DataIntegrityProof {
            type_: "test".to_string(),
            created: None,
            context: None,
            cryptosuite: CryptoSuite::EddsaJcs2022,
            proof_purpose: "test".to_string(),
            proof_value: None,
            verification_method: "did:key:z6MktestNoHash".to_string(),
        };
        let err = proof.get_public_key_bytes().unwrap_err();
        // resolve_did_key fails to decode the multibase body because
        // "z6MktestNoHash" is not a valid base58btc multicodec payload.
        assert!(
            matches!(err, DIDWebVHError::InvalidMethodIdentifier(_)),
            "expected InvalidMethodIdentifier, got {err:?}"
        );
    }

    /// Tests that a well-formed did:key verification method with a valid ed25519
    /// multikey successfully extracts non-empty public key bytes.
    /// Expected: Returns a non-empty byte vector representing the public key.
    /// This matters because valid key extraction is the prerequisite for
    /// verifying data integrity proofs on log entries.
    #[test]
    fn test_public_key_valid() {
        // Use a real ed25519 multikey
        let secret = affinidi_secrets_resolver::secrets::Secret::generate_ed25519(None, None);
        let pk = secret.get_public_keymultibase().unwrap();
        let proof = DataIntegrityProof {
            type_: "test".to_string(),
            created: None,
            context: None,
            cryptosuite: CryptoSuite::EddsaJcs2022,
            proof_purpose: "assertionMethod".to_string(),
            proof_value: None,
            verification_method: format!("did:key:{pk}#{pk}"),
        };
        let bytes = proof.get_public_key_bytes().unwrap();
        assert!(!bytes.is_empty());
    }

    // ===== deserialize_string() tests =====

    /// Tests that deserializing a non-JSON string returns an error.
    /// Expected: Returns a deserialization error.
    /// This matters because log entries are transmitted as JSON; malformed input
    /// must be caught early to prevent downstream processing of invalid data.
    #[test]
    fn test_deserialize_invalid_json_error() {
        let result = LogEntry::deserialize_string("not json", None);
        assert!(result.is_err());
    }

    /// Tests that valid JSON lacking a "parameters" field fails deserialization
    /// for the V1_0 spec variant.
    /// Expected: Returns an error because the parameters block is required.
    /// This matters because every WebVH log entry must carry parameters (method,
    /// scid, updateKeys, etc.) to be a valid entry in the DID log.
    #[test]
    fn test_deserialize_missing_parameters_error() {
        // Valid JSON but no parameters field — for V1_0, it checks for parameters
        let json = r#"{"versionId":"1-abc","versionTime":"2024-01-01T00:00:00Z","state":{}}"#;
        let result = LogEntry::deserialize_string(json, None);
        assert!(result.is_err());
    }

    /// Tests that a properly serialized Spec1_0 log entry round-trips through
    /// deserialize_string and is recognized as the Spec1_0 variant.
    /// Expected: Returns Ok with a LogEntry::Spec1_0 variant.
    /// This matters because correct version detection ensures log entries are
    /// parsed with the right schema, maintaining interoperability.
    #[test]
    fn test_deserialize_v1_0_ok() {
        let json = serde_json::to_string(&LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({"id": "did:webvh:scid:example.com"}),
            proof: vec![],
        }))
        .unwrap();
        let result = LogEntry::deserialize_string(&json, None).unwrap();
        assert!(matches!(result, LogEntry::Spec1_0(_)));
    }

    /// Tests that JSON with null-valued parameter fields (e.g. "updateKeys": null)
    /// is detected as the pre-ratification Spec1_0Pre variant rather than Spec1_0.
    /// Expected: Returns Ok with a LogEntry::Spec1_0Pre variant.
    /// This matters because the pre-ratified spec used JSON nulls instead of empty
    /// arrays/objects; distinguishing the two ensures backward compatibility with
    /// DIDs created before the spec was finalized.
    #[test]
    fn test_deserialize_detects_pre_version_nulls() {
        // JSON with null values in parameters should trigger Spec1_0Pre
        let json = r#"{"versionId":"1-abc","versionTime":"2024-01-01T00:00:00Z","parameters":{"method":"did:webvh:1.0","scid":"test","updateKeys":null},"state":{}}"#;
        let result = LogEntry::deserialize_string(json, None).unwrap();
        assert!(matches!(result, LogEntry::Spec1_0Pre(_)));
    }

    // ===== from_string_to_known_version() tests =====

    /// Tests that from_string_to_known_version correctly parses a string as
    /// the Spec1_0 variant when Version::V1_0 is explicitly specified.
    /// Expected: Returns Ok with a LogEntry::Spec1_0 variant.
    /// This matters because when the version is already known (e.g. from a
    /// previous log entry), skipping auto-detection is more efficient and avoids
    /// ambiguity.
    #[test]
    fn test_from_string_v1_0() {
        let json = serde_json::to_string(&LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({}),
            proof: vec![],
        }))
        .unwrap();
        let result = LogEntry::from_string_to_known_version(&json, Version::V1_0).unwrap();
        assert!(matches!(result, LogEntry::Spec1_0(_)));
    }

    /// Tests that from_string_to_known_version correctly parses a string with
    /// null-valued parameters as the Spec1_0Pre variant when Version::V1_0Pre
    /// is explicitly specified.
    /// Expected: Returns Ok with a LogEntry::Spec1_0Pre variant.
    /// This matters because pre-ratified log entries use a different serialization
    /// format (nulls vs empty collections) and must be parsed with the correct
    /// deserializer to avoid data loss.
    #[test]
    fn test_from_string_v1_0_pre() {
        // Spec1_0Pre uses null serialization, construct manually
        let json = r#"{"versionId":"1-abc","versionTime":"2024-01-01T00:00:00Z","parameters":{"method":"did:webvh:1.0","scid":"test","updateKeys":null,"nextKeyHashes":null,"witness":null,"watchers":null,"deactivated":null,"ttl":null},"state":{}}"#;
        let result = LogEntry::from_string_to_known_version(json, Version::V1_0Pre).unwrap();
        assert!(matches!(result, LogEntry::Spec1_0Pre(_)));
    }

    // ===== get_did_document() tests =====

    /// Tests that get_did_document adds implicit services (whois, files) alongside
    /// any explicit services defined in the DID document state.
    /// Expected: The returned document contains 3 services (1 custom + 2 implicit).
    /// This matters because the WebVH spec requires certain implied services to be
    /// present in the resolved DID document even when they are not stored in the
    /// log entry state.
    #[test]
    fn test_get_did_document_with_services() {
        let entry = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({
                "id": "did:webvh:scid123:example.com",
                "service": [{
                    "id": "did:webvh:scid123:example.com#custom",
                    "type": "Custom",
                    "serviceEndpoint": "https://example.com"
                }]
            }),
            proof: vec![],
        });
        let doc = entry.get_did_document().unwrap();
        let services = doc["service"].as_array().unwrap();
        // Should have original + whois + files = 3
        assert_eq!(services.len(), 3);
    }

    /// Tests that get_did_document returns an error when the DID document state
    /// is missing the required "id" field.
    /// Expected: Returns an error referencing the missing "id".
    /// This matters because the DID document id is essential for constructing
    /// implied service endpoints; without it, the document cannot be resolved.
    #[test]
    fn test_get_did_document_missing_id_error() {
        let entry = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({"noId": true}),
            proof: vec![],
        });
        let err = entry.get_did_document().unwrap_err();
        assert!(err.to_string().contains("id"));
    }

    // ===== save_to_file() and generate_log_entry_hash() tests =====

    /// Tests that a log entry can be saved to a JSONL file and loaded back with
    /// identical content, verifying the file I/O round-trip.
    /// Expected: The loaded entry has the same versionId and exactly one entry.
    /// This matters because the DID log file is the persistent representation of
    /// all version history; data must survive serialization without corruption.
    #[test]
    fn test_save_and_load_roundtrip() {
        let entry = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({"id": "did:webvh:scid:example.com"}),
            proof: vec![],
        });
        let unique_name = format!(
            "didwebvh_test_save_roundtrip_{}.jsonl",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(unique_name);
        let path_str = path.to_str().unwrap();
        entry.save_to_file(path_str).unwrap();
        let loaded = LogEntry::load_from_file(path_str).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].get_version_id(), "1-abc");
        let _ = std::fs::remove_file(path);
    }

    /// Repeated hash calls on the same value are stable — trivial idempotence.
    #[test]
    fn test_generate_hash_deterministic() {
        let entry = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({"id": "did:webvh:scid:example.com"}),
            proof: vec![],
        });
        let hash1 = entry.generate_log_entry_hash().unwrap();
        let hash2 = entry.generate_log_entry_hash().unwrap();
        assert_eq!(hash1, hash2);
    }

    // ===== JCS canonicalisation guarantees =====
    //
    // These tests pin down the two halves of RFC 8785's canonical form on the
    // surface that matters most for didwebvh — the `service` block in
    // `state`:
    //
    //   1. Object-key ORDER is normalised (sorted) — different key
    //      insertion orders MUST produce the same hash.
    //   2. Array-element ORDER is preserved — different service ordering
    //      MUST produce different hashes.
    //
    // If either of these regresses (e.g. someone swaps the canonicalizer
    // crate or accidentally pre-sorts arrays), the entry hash and SCID will
    // silently diverge from every other didwebvh implementation. Catching
    // that here is much cheaper than catching it via a failed interop test.

    /// JCS sorts object keys: two service blocks whose object-keys are in
    /// different insertion order MUST hash identically. Inputs are built as
    /// raw JSON strings (not via `json!`) because `serde_json::Value` already
    /// pre-sorts via its `BTreeMap` backing — going through string parsing
    /// keeps the test honest about what the canonicalizer is doing.
    #[test]
    fn test_jcs_sorts_service_object_keys() {
        // r##"..."## (double-#) so the JSON `"#a"` doesn't terminate the raw string.
        let state_a: serde_json::Value = serde_json::from_str(
            r##"{
                "id": "did:webvh:scid:example.com",
                "service": [
                    {"id": "#a", "type": "X", "serviceEndpoint": "https://a"}
                ]
            }"##,
        )
        .unwrap();
        let state_b: serde_json::Value = serde_json::from_str(
            r##"{
                "service": [
                    {"serviceEndpoint": "https://a", "type": "X", "id": "#a"}
                ],
                "id": "did:webvh:scid:example.com"
            }"##,
        )
        .unwrap();

        let now = Utc::now().fixed_offset();
        let mk = |state| {
            LogEntry::Spec1_0(LogEntry1_0 {
                version_id: "1-abc".to_string(),
                version_time: now,
                parameters: Parameters1_0::default(),
                state,
                proof: vec![],
            })
        };

        assert_eq!(
            mk(state_a).generate_log_entry_hash().unwrap(),
            mk(state_b).generate_log_entry_hash().unwrap(),
            "JCS must sort object keys — key insertion order must not affect hash",
        );
    }

    /// JCS preserves array order: swapping two services in the `service`
    /// array MUST change the hash. RFC 8785 §3.2.4 says array order is
    /// preserved, so different orderings are different documents and must
    /// hash differently.
    #[test]
    fn test_jcs_preserves_service_array_order() {
        let svc_a = json!({"id": "#a", "type": "X", "serviceEndpoint": "https://a"});
        let svc_b = json!({"id": "#b", "type": "Y", "serviceEndpoint": "https://b"});

        let now = Utc::now().fixed_offset();
        let mk = |services: Vec<serde_json::Value>| {
            LogEntry::Spec1_0(LogEntry1_0 {
                version_id: "1-abc".to_string(),
                version_time: now,
                parameters: Parameters1_0::default(),
                state: json!({
                    "id": "did:webvh:scid:example.com",
                    "service": services,
                }),
                proof: vec![],
            })
        };

        let hash_ab = mk(vec![svc_a.clone(), svc_b.clone()])
            .generate_log_entry_hash()
            .unwrap();
        let hash_ba = mk(vec![svc_b, svc_a]).generate_log_entry_hash().unwrap();

        assert_ne!(
            hash_ab, hash_ba,
            "JCS preserves array order — swapping services must change the hash",
        );
    }

    /// Top-level array order matters too (e.g. `verificationMethod`,
    /// `authentication`, `updateKeys` in parameters). Same property as
    /// services but worth pinning down independently because these are
    /// strongly-typed `Vec` fields rather than raw JSON arrays.
    #[test]
    fn test_jcs_preserves_authentication_array_order() {
        let now = Utc::now().fixed_offset();
        let mk = |refs: Vec<&str>| {
            LogEntry::Spec1_0(LogEntry1_0 {
                version_id: "1-abc".to_string(),
                version_time: now,
                parameters: Parameters1_0::default(),
                state: json!({
                    "id": "did:webvh:scid:example.com",
                    "authentication": refs,
                }),
                proof: vec![],
            })
        };

        let hash_ab = mk(vec!["#k1", "#k2"]).generate_log_entry_hash().unwrap();
        let hash_ba = mk(vec!["#k2", "#k1"]).generate_log_entry_hash().unwrap();

        assert_ne!(hash_ab, hash_ba);
    }

    /// `get_did_document()` must NOT mutate the LogEntry. After calling it,
    /// the LogEntry's stored `state` must be unchanged (no implicit services
    /// folded in) and `generate_log_entry_hash()` must return the same value
    /// as before the call. This is the core hash-chain safety invariant: if
    /// `get_did_document()` ever mutated `state` in-place, every subsequent
    /// signature and version hash would diverge from every other
    /// implementation.
    #[test]
    fn test_get_did_document_does_not_affect_hash() {
        let entry = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({
                "id": "did:webvh:scid123:example.com",
                "service": [
                    {"id": "#custom", "type": "Custom", "serviceEndpoint": "https://example.com"}
                ]
            }),
            proof: vec![],
        });

        let hash_before = entry.generate_log_entry_hash().unwrap();
        let state_before = entry.get_state().clone();

        // Building the resolution-time DID Document MUST be read-only.
        let resolved = entry.get_did_document().unwrap();
        let resolved_services = resolved["service"].as_array().unwrap();
        assert_eq!(
            resolved_services.len(),
            3,
            "resolution adds #files + #whois"
        );

        // The LogEntry itself must be untouched.
        assert_eq!(entry.get_state(), &state_before, "state must not mutate");
        assert_eq!(entry.get_state()["service"].as_array().unwrap().len(), 1);
        assert_eq!(
            entry.generate_log_entry_hash().unwrap(),
            hash_before,
            "hash must not change after get_did_document()",
        );
    }

    // ===== create() tests =====

    /// Tests that attempting to create a new log entry with the pre-ratification
    /// version (V1_0Pre) returns an error.
    /// Expected: Returns an error indicating version must be 1.0 or higher.
    /// This matters because new DIDs must only be created using the ratified spec;
    /// the pre-ratification format exists solely for backward-compatible reading.
    #[test]
    fn test_create_v1_0_pre_error() {
        let result = LogEntry::create(
            "1-test".to_string(),
            Utc::now().fixed_offset(),
            Parameters::default(),
            json!({}),
            Version::V1_0Pre,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("1.0 or higher"));
    }

    // ===== parse_version_id_fields() tests =====

    /// Tests that a well-formed versionId string "3-abc123" is correctly split
    /// into the numeric version (3) and the hash component ("abc123").
    /// Expected: Returns (3, "abc123").
    /// This matters because the versionId encodes both the sequence number and
    /// the entry hash; correct parsing is required for version chain validation.
    #[test]
    fn test_parse_version_id_valid() {
        let (num, hash) = parse_version_id_fields("3-abc123").unwrap();
        assert_eq!(num, 3);
        assert_eq!(hash, "abc123");
    }

    /// Tests that a versionId string without a dash separator returns an error.
    /// Expected: Returns an error referencing "versionID" format.
    /// This matters because the "<number>-<hash>" format is mandated by the spec;
    /// strings that do not follow this pattern indicate a corrupted or malformed log.
    #[test]
    fn test_parse_version_id_missing_dash() {
        let err = parse_version_id_fields("noDash").unwrap_err();
        assert!(err.to_string().contains("versionID"));
    }

    /// Tests that a versionId whose numeric portion is not a valid u32 returns
    /// an error.
    /// Expected: Returns an error about failing to parse the version ID.
    /// This matters because the version number must be a positive integer for
    /// sequential ordering of log entries; non-numeric values break chain validation.
    #[test]
    fn test_parse_version_id_non_numeric() {
        let err = parse_version_id_fields("abc-hash").unwrap_err();
        assert!(err.to_string().contains("Failed to parse version ID"));
    }

    // ===== get_webvh_version() test =====

    /// Tests that get_webvh_version correctly reports Version::V1_0 for a
    /// Spec1_0 log entry variant.
    /// Expected: Returns Version::V1_0.
    /// This matters because the version tag determines which serialization rules
    /// and validation logic apply when processing subsequent log entries.
    #[test]
    fn test_get_webvh_version() {
        let entry_1_0 = LogEntry::Spec1_0(LogEntry1_0 {
            version_id: "1-abc".to_string(),
            version_time: Utc::now().fixed_offset(),
            parameters: Parameters1_0::default(),
            state: json!({}),
            proof: vec![],
        });
        assert_eq!(entry_1_0.get_webvh_version(), Version::V1_0);
    }
}